Sub topic 2
The img element as the baseline and fallback
This chapter covers the img element on its own. Later chapters add srcset, sizes, and picture on top of it. You need to understand what img does first, because every responsive technique in this tutorial still ends in an img.
You should already know basic HTML (elements, attributes, the src and alt attributes) and the difference between a CSS pixel and a device pixel. Later chapters assume you also know media queries and viewport units.
What img actually does
An img is a replaced element. The browser fetches an external resource and draws it in place of the element. The element has no children and no closing tag.
A minimal, valid image looks like this:
<img src="photo-800.jpg" alt="A lighthouse on a rocky coast at sunset">Here is what happens when the browser meets this element:
- The parser creates an
imgelement and reads its attributes. - The browser starts a request for the URL in
src, resolved against the page's base URL. - When the response arrives, the browser decodes the file and paints it. Until then the element has no intrinsic size, unless you gave it one (see the section on width and height below).
- If the request fails or the file cannot be decoded, the browser shows the
alttext instead, usually with a broken-image icon.
The key point for this tutorial is that the browser needs exactly one URL to make this work. Responsive images give the browser more than one choice. They never remove the need for that one URL.
The roles of src
src plays three roles at once.
- Default resource. With no other attributes,
srcis the file that is loaded. - Fallback for older software. A browser that does not understand
srcsetorpictureignores those features and loadssrc. Very old browsers, some email clients, and some feed readers behave this way. - Last-resort candidate. Modern browsers still use
srcin some cases, described below.
The third role depends on which descriptors you use in srcset:
| `srcset` content | How `src` is used |
|---|---|
| No `srcset` | `src` is the only candidate. |
| `x` descriptors | `src` is added as a 1x candidate if `srcset` does not already list a 1x file. |
| `w` descriptors | `src` is not a candidate. Browsers that support `w` ignore it, and only older browsers use it. |
Because of the last row, choose the src of a w-based image as a safe middle size, not the smallest or the largest. Old browsers get exactly that file. A file that is too small looks blurry for them, and one that is too large wastes their bandwidth. For a layout that tops out at 1600 pixels wide, an 800-pixel file is a reasonable compromise.
This is how a complete responsive img looks, with its fallback in place:
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
sizes="(min-width: 60em) 33vw, 100vw"
width="1600"
height="1200"
alt="A lighthouse on a rocky coast at sunset">You do not need to understand srcset and sizes yet. Notice only that src is still present and still points to a real, usable file.
The img inside picture
The picture element is a wrapper. It holds zero or more source elements and exactly one img. The img is not optional.
<picture>
<source type="image/avif" srcset="photo.avif">
<source type="image/webp" srcset="photo.webp">
<img src="photo.jpg" width="800" height="600" alt="A lighthouse on a rocky coast at sunset">
</picture>Three facts about this structure cause most beginner mistakes:
- The
imgis what renders. The browser may pick a file from asource, but it displays that file through theimgelement. Thepictureandsourceelements are never drawn. - The
imgsupplies the fallback. If nosourcematches, or the browser does not knowpicture, it loads theimgas if the wrapper were not there. - Attributes that describe the image belong on the
img.alt,width,height,loading,class, andidall go on theimg. Puttingalton asourceor on thepicturedoes nothing.
CSS follows the same rule. Selectors such as picture img { max-width: 100%; height: auto; } style the element that is actually drawn. Styling picture itself rarely does what you expect, because it is an inline element by default and does not act as the image box.
Writing good alt text
The alt attribute gives a text equivalent of the image. Screen readers announce it. Browsers show it when the image fails to load. Search engines use it to understand the image. It is required for valid HTML, with one narrow exception for some embedded contexts. Treat it as always required.
The right value depends on what the image is for.
| Image purpose | What to write in `alt` |
|---|---|
| Informative photo or illustration | A short description of what matters in context. |
| Image that contains text, such as a logo or banner | The text in the image. |
| Link or button made of an image | What the link does or where it goes, not what the picture looks like. |
| Purely decorative image | An empty value: `alt=""`. |
| Chart or diagram | A short summary, with the full data in the surrounding text. |
Two points are worth stressing.
First, alt="" and a missing alt are different. An empty value tells assistive technology to skip the image, which is correct for decoration. A missing attribute leaves the screen reader to guess, and many read out the file name, such as "photo-800 dot jpg".
Second, do not start with "Image of" or "Picture of". Screen readers already announce that the element is an image. Compare these two:
<!-- Weak: repeats information the screen reader already gives -->
<img src="photo-800.jpg" alt="Image of a photo of a lighthouse">
<!-- Better: says what the image shows -->
<img src="photo-800.jpg" alt="A lighthouse on a rocky coast at sunset">With art direction, different crops show the same subject, so one alt serves all of them. Write a description that stays true for every crop. If a crop shows something the others do not, and that matters to the reader, add the information to the surrounding text.
Sizing the img element
The width and height attributes give the browser the image's dimensions before the file arrives. Modern browsers use them to work out the aspect ratio and reserve space, so the page does not jump when the image loads. A later chapter covers this in detail. For now, include both attributes on every img and use the file's real pixel dimensions, or at least their correct ratio.
The usual CSS pairing keeps the image fluid:
img {
max-width: 100%;
height: auto;
}With this rule, the attributes set the aspect ratio and the CSS lets the image shrink to fit its container. Without height: auto, a shrunken image keeps the attribute height and gets distorted.
Checking the baseline in practice
You can confirm what a browser chose through the DOM. The currentSrc property reports the URL of the file that is in use, even when it came from srcset or a source element. Plain src always reports the attribute value, which makes currentSrc the more useful one for debugging.
const img = document.querySelector('img');
console.log(img.src);
console.log(img.currentSrc);
console.log(img.complete, img.naturalWidth);For a plain img with no srcset, src and currentSrc are identical once the image has been selected. naturalWidth is the file's own width in pixels, and it is 0 if the file has not loaded or failed to load. Read these values after the load event, or check img.complete first, because currentSrc can be an empty string before the browser has made its choice.
Common errors
- Omitting
srcwhensrcsetis present. The page may appear to work in current browsers, but the HTML is invalid and old browsers show nothing. Always includesrc. - Pointing
srcat a missing or tiny file. The fallback is only useful if it is a good image. Test it by temporarily removingsrcset. - Omitting the
imginsidepicture. Thepicturedoes nothing without it, and nothing displays. - Putting
alt,width, orloadingonsource. These belong on theimg. - Writing
alt="image"or repeating the file name. This is noise for screen reader users. Describe the content or use an empty value. - Using
srcwith a different image thansrcset. The fallback should depict the same content, or older browsers show a different picture from everyone else.
Exercise
A page uses <img src="team-800.jpg" srcset="team-400.jpg 400w, team-800.jpg 800w, team-1600.jpg 1600w" sizes="100vw" width="1600" height="1000" alt=""> for a photo of the team that sits next to the heading "Meet the team". Name two things that are wrong or questionable, and say who is affected by each.
Show answer
First, alt="" marks the photo as decorative, so screen reader users get no information about it. A photo of the team is informative, so it should have a description such as "Five members of the support team standing in front of the office". Second, src is a 800-pixel file, which is a sensible fallback, but the page should check that team-800.jpg really matches the content of the other files. Otherwise older browsers that ignore srcset and sizes would show something different. If the file is correct, only the alt text needs to change. The affected users for the first problem are people using screen readers or text-only browsers, and anyone whose image fails to load.
Exercise
You wrap an image in picture with two source elements for AVIF and WebP, but you forget the img. What does the browser show, and why?
Show answer
It shows nothing. The browser draws images through the img element, so picture and source only influence which file the img loads. Without an img, there is nothing to render and no fallback. The fix is to add <img src="photo.jpg" width="800" height="600" alt="..."> as the last child of picture.