How to Add Images in HTML with the Tag Explained

Images are essential for creating engaging web pages. In HTML, we use the <img> tag to embed them.

The image tag is a "void element," meaning it is self-closing and does not have a closing tag. It requires two essential attributes: src and alt.

Analogy: Think of an image like a framed picture on the wall. The src attribute is a map telling the browser where to find the picture. The alt attribute is a description written on the back for someone who can't see the front.

The src Attribute (Source)

This tells the browser the path to the image file.

<!-- Linking to an image on another website -->
<img src="https://via.placeholder.com/150">

<!-- Linking to an image in an "images" folder on your site -->
<img src="/images/logo.png">

The alt Attribute (Alternative Text)

This provides a text description of the image. It is the single most important attribute for images.

  1. Accessibility: Screen readers read the alt text aloud to visually impaired users.

  2. SEO: Google uses alt text to understand what an image is about, helping it rank in image search.

  3. Broken Images: If the image fails to load, the alt text will be displayed in its place.

Good alt text:
<img src="puppy.jpg" alt="A golden retriever puppy playing with a red ball">

Best Practice Tip: Always specify the width and height attributes for your images. This allows the browser to reserve the correct amount of space for the image before it has even loaded, preventing the page content from jumping around.
<img src="logo.png" alt="logo" width="200" height="50">

What's Next: We've now covered all the essential tags for adding and formatting content. In our next lesson, we'll review this chapter and tackle common interview questions.


Posted in 02 - Core Content & Text Formatting and tagged , , , .

Leave a Reply