Sub topic 11
Images and the alt attribute
This chapter assumes you can write a basic HTML document, know what elements and attributes are, and understand relative and absolute URLs from the previous chapter on links. Here you will learn how the img element works, why alt is the most important attribute on it, and how to avoid the common mistakes.
The img element
An image is added with the img element. It is a void element, so it has no content and no end tag. Everything it needs is in its attributes.
<img src="cat.jpg" alt="A grey cat asleep on a sofa" width="400" height="300">Two attributes are required for a valid img:
srcgives the URL of the image file. The browser downloads it and draws it where the element sits.altgives a text alternative. It is used when the image cannot be seen.
width and height are not required, but you should almost always include them (see below).
The img element is inline by default. It sits in the flow of a line of text, like a very large character. If you put it directly in body, it is still valid, but you will usually wrap it in a paragraph, a figure, or a link.
Paths in src
The src value is a URL, so the same rules as for links apply. Relative paths are resolved against the URL of the current page, not against the image's location.
| `src` value | Meaning |
|---|---|
| `cat.jpg` | A file in the same folder as the page |
| `images/cat.jpg` | A file in an `images` subfolder |
| `../images/cat.jpg` | A file in an `images` folder one level up |
| `/images/cat.jpg` | A file in `images` at the root of the site |
| `https://example.com/cat.jpg` | A file on another site |
Linking to images on someone else's server is fragile. The owner can move or delete the file, and your page breaks. Host the images you depend on with your page when you can.
File names are case-sensitive on many servers. Cat.JPG and cat.jpg may work on your laptop and fail once the site is uploaded. Use lowercase names with hyphens, and avoid spaces.
What alt is for
The alt attribute holds a text replacement for the image. It is used in several situations:
- A screen reader reads it aloud to a person who cannot see the image.
- The browser shows it in place of the image when the file fails to load or the connection is slow.
- Search engines use it to understand what the image shows.
- A text-only browser or a reading mode shows it instead of the picture.
The test for good alt text is: if the image vanished, what words would you put in its place so the page still makes sense? The answer depends on why the image is on the page.
<!-- The image carries information -->
<img src="chart-2026.png" alt="Bar chart: sales rose from 40 units in January to 95 in June">
<!-- The image is the content of a link -->
<a href="/">
<img src="logo.svg" alt="Garden Notes home" width="160" height="40">
</a>
<!-- The image is purely decoration -->
<img src="divider.png" alt="" width="600" height="8">Choosing the right text
Some guidelines that follow from this:
- Describe the purpose, not just the appearance. A photo of a bridge on a travel page might need "Golden Gate Bridge in morning fog". The same photo in an engineering article might need "Suspension cables meeting the main tower".
- Keep it short. One sentence is usually enough. If an image such as a complex chart needs more, put the longer explanation in the page text or a nearby table and keep
altas a summary. - Do not begin with "image of" or "picture of". Screen readers already announce that the element is an image.
- Do not stuff keywords. Alt text written for search engines instead of people makes the page worse for both.
- For an image inside a link, describe where the link goes. "Home" is more useful than "logo".
Empty alt versus missing alt
These two cases look similar but behave differently.
alt=""says "this image is decorative". Screen readers skip it completely.- A missing
altattribute says nothing. Many screen readers fall back to reading the file name, such as "IMG underscore 4021 dot jpg", which is noise. A validator reports it as an error.
alt is not title
The title attribute produces a tooltip on mouse hover only. It is not available on touch screens, is not reliably read by assistive technology, and cannot replace alt. Use alt for the text alternative. Leave title out unless you have a specific reason to add it.
Width, height and layout shift
A browser does not know how large an image is until it has downloaded at least part of the file. Without size information, it lays out the text first and then pushes everything down when the image arrives. This jump is called layout shift, and it is annoying to read through.
Setting width and height as plain numbers (pixels, with no unit) lets the browser reserve the right amount of space before the file arrives. Use the image's real pixel size, or at least its correct proportions. If your CSS later resizes the image, for example with max-width: 100% and height: auto, the browser uses these two values to keep the aspect ratio.
<img src="harvest.jpg" alt="A basket of ripe tomatoes on a wooden table" width="800" height="533">Do not use width and height to shrink a huge file. The browser still downloads all of it. Resize the file itself before you publish it.
Choosing a file format
| Format | Best for | Notes |
|---|---|---|
| JPEG | Photographs | Lossy, small files, no transparency |
| PNG | Screenshots, graphics with sharp edges | Lossless, supports transparency, larger for photos |
| SVG | Logos, icons, simple diagrams | Vector format, scales without blur, text-based |
| WebP and AVIF | Photos and graphics | Smaller than JPEG or PNG at similar quality, supported by current browsers |
| GIF | Very short simple animations | Limited to 256 colours, large files |
Loading and responsive images
Two additions help performance without changing how the page looks.
The loading="lazy" attribute tells the browser to delay downloading an image until the user scrolls near it. Use it on images below the first screen. Do not use it on the main image at the top, because that delays what the visitor sees first.
The srcset and sizes attributes let you supply several versions of one image. The browser picks the best one for the screen width and pixel density.
<img
src="harvest-800.jpg"
srcset="harvest-400.jpg 400w, harvest-800.jpg 800w, harvest-1600.jpg 1600w"
sizes="(max-width: 600px) 100vw, 800px"
alt="A basket of ripe tomatoes on a wooden table"
width="800"
height="533"
loading="lazy">Each entry in srcset is a file name followed by its width in pixels with a w suffix. sizes says how wide the image will be displayed, so the browser can choose before it loads the CSS. The src value remains as a fallback for browsers that do not understand srcset. The alt text is the same for every version, because they are all the same picture.
When you need different formats or a different crop for different screens, wrap the image in a picture element. The browser uses the first source it supports and falls back to the img.
<picture>
<source type="image/avif" srcset="harvest.avif">
<source type="image/webp" srcset="harvest.webp">
<img src="harvest.jpg" alt="A basket of ripe tomatoes on a wooden table" width="800" height="533">
</picture>The img inside picture is required. It carries the alt text and is what is actually displayed. Putting alt on a source has no effect.
Captions with figure
A caption is visible text that belongs to an image. Use figure and figcaption to connect them.
<figure>
<img src="harvest.jpg" alt="A basket of ripe tomatoes on a wooden table" width="800" height="533">
<figcaption>Figure 1. The first tomato harvest of the season.</figcaption>
</figure>The caption and the alt text serve different purposes. The caption is for everyone and adds context. The alt text stands in for the picture. If both say the same thing, a screen reader user hears it twice, so make the alt describe the picture and the caption explain why it is there. If the caption already describes the image completely, alt="" is acceptable.
Common errors
- Missing
alt. The validator flags it, and screen reader users hear the file name. - Using
altfor a long essay. Move the details into the page text. - Putting text in an image, such as a banner with a headline drawn into it. The text cannot be selected, scaled or translated. Use real text styled with CSS, and reserve images for pictures.
- Writing
<img src="cat.jpg" />and expecting the slash to matter. It is allowed but ignored in HTML. There is no</img>. - Wrong path or file name case. Open the browser developer tools, look at the Network tab, and check for a 404 response on the image.
- Using
width="400px". The attribute takes a number only. - Forgetting that lazy loading on the top image slows the first view.
Exercise
A page has a small decorative line image between two sections, and a logo that links to the home page. Write the img elements for both, and explain what a screen reader does with each one.
Show answer
Decorative line: <img src="divider.png" alt="" width="600" height="8">. The empty alt tells a screen reader to skip it. Logo: <a href="/"><img src="logo.svg" alt="Garden Notes home" width="160" height="40"></a>. The screen reader announces the link and reads the alt text as its name, so the alt describes the destination, not the look of the logo.
Exercise
Why should you set width and height on an img, and what happens if you set alt="image of a cat" instead of a useful description?
Show answer
Width and height let the browser reserve space before the file downloads, which prevents layout shift. The alt "image of a cat" wastes words ("image of" is already announced) and says nothing about what matters in the picture. Something like "A grey cat asleep on a sofa" gives the actual content.