Lesson 8 of 1844%

(Progress persistence is disabled until Phase 9)

HTML
Beginner
10 min

Images and Alternative Text

Learn how to embed images into your webpages and ensure they are accessible.

Learning Objectives

  • Learn how to use the img tag
  • Understand the src attribute
  • Understand the critical importance of the alt attribute

The Image Tag

To display an image on a webpage, we use the <img> tag.

Just like the <br> tag we learned about earlier, the <img> tag is an empty element. It does not wrap around any text content, so it does not have a closing tag!

To make the image appear, we must use two mandatory attributes: src and alt.

The src Attribute

The src (source) attribute tells the browser where the image file is located. Just like links, this can be an absolute URL (an image hosted on another website) or a relative URL (an image file in your own project folder).

Syntax / Structure

<img src="URL" alt="Description">

The alt Attribute (Crucial!)

The alt (alternative text) attribute provides a text description of the image. This is critically important for three reasons:

  1. Accessibility: Screen readers cannot “see” images. They rely entirely on reading the alt text out loud so visually impaired users understand what the image shows.
  2. Fallback: If the image fails to load (due to a bad internet connection or a broken link), the browser will display the alt text instead.
  3. SEO: Search engines like Google use alt text to understand the content of the image.
Warning

A bad alt attribute: alt="photo of dog.jpg"

A good alt attribute: alt="A golden retriever playing catch in the park"

Code Example

Here is a complete example of embedding an image:

<p>Here is a picture of my pet cat:</p>
<img src="/images/fluffy.jpg" alt="A fluffy orange tabby cat sleeping on a blue cushion">

Sizing Images

You can use the width and height attributes to tell the browser how large the image should be (in pixels). However, modern developers usually control image sizing using CSS to make the images responsive to different screen sizes.

Try It Yourself

Try adding an image to the playground using a random image URL like https://picsum.photos/200/300.

Key Takeaways

  • The <img> tag is an empty element (no closing tag).
  • The src attribute is required to tell the browser where to find the image.
  • The alt attribute is mandatory for accessibility and should describe the image contents accurately.

Lesson Progress

Take QuizBuild a HTML Project