Sub topic 7
Reserving space with width and height
This chapter assumes you know basic HTML (img, src, alt), basic CSS (media queries, max-width), and the difference between CSS pixels and device pixels. It also assumes you have read the earlier chapters on srcset and sizes. Here you will learn why the browser needs to know an image's shape before the file arrives, and how the width and height attributes give it that information.
The problem: layout shift
A browser reads HTML from top to bottom and starts laying out the page right away. Images are fetched separately, so they usually arrive after the text around them. If an img has no size information, the browser has no idea how tall it will be. It gives the image a height of 0 pixels, or the height of its alt text, and lays out the following content directly beneath it.
When the file finally arrives, the browser learns the real dimensions and makes room. Everything below the image jumps down. This is called layout shift. Readers see it as text that moves while they are reading, or as a button that moves just before they tap it.
Browsers measure this with the Cumulative Layout Shift (CLS) metric, which is one of the Core Web Vitals. A lower score is better. Missing image dimensions are one of the most common causes of a poor score, and they are among the easiest to fix.
What the attributes do
The width and height attributes on an img take plain integers with no unit. They are measured in CSS pixels.
<img
src="photo-800.jpg"
width="800"
height="600"
alt="A lighthouse on a rocky coast at sunset">Before the file loads, this tells the browser that the image is 800 pixels wide and 600 pixels tall. Writing width="800px" is invalid. Use 800.
Historically these attributes only set a fixed size. Modern browsers do something more useful with them. They read the two numbers, compute the ratio (here 800 / 600, or 4:3), and apply it as the default aspect-ratio of the image box. This works even when CSS changes the displayed width, which is the case for nearly every responsive layout.
Making it work with fluid layouts
Most responsive pages include a rule like this:
img {
max-width: 100%;
height: auto;
}The height: auto part matters. Without it, the CSS would keep the height attribute as a fixed height (for example 600 pixels) even when max-width shrinks the image to 320 pixels wide. The result would be a squashed or stretched picture.
With height: auto, the browser works out the height from the aspect ratio that the attributes supplied. A 4:3 image shown 320 pixels wide gets a 240-pixel-tall box, reserved before the file loads.
Here is a complete page you can open in a browser. Throttle the network in developer tools (covered in a later chapter) to watch the box appear before the image does.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Reserved space</title>
<style>
body { max-width: 40em; margin: 0 auto; padding: 1em; }
img { max-width: 100%; height: auto; }
</style>
</head>
<body>
<h1>Harbor notes</h1>
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
sizes="(min-width: 40em) 40em, 100vw"
width="1600"
height="1200"
alt="A lighthouse on a rocky coast at sunset">
<p>This paragraph stays in place while the image downloads.</p>
</body>
</html>Which numbers to use
The attribute values are not the display size. They describe the image's shape, and the file's own proportions are what matter. Two rules cover most cases.
- Use the intrinsic size of one of your files, or any pair with the same ratio. If your largest file is 1600 by 1200, writing
width="1600" height="1200"is correct. - Keep the ratio identical across every candidate in a
srcset. Ifphoto-400.jpgis 400 by 300 butphoto-1600.jpgis 1600 by 1100, the ratios differ and the layout will shift when the browser switches files.
The width and height of the 1x file are a common choice with x descriptors, as in the first example of the series: a 400-pixel file for 1x and an 800-pixel file for 2x, with width="400" height="300". The attributes describe the display size at 1x, and the 2x file simply has twice as many pixels in the same box.
How this interacts with `sizes`
The attributes and sizes answer different questions, and they do not conflict.
| Feature | Question it answers | Affects |
|---|---|---|
| `width` and `height` | What shape is the image? | Reserved box and aspect ratio |
| `sizes` | How wide will the box be on screen? | Which file the browser downloads |
| `srcset` | What files exist and how wide are they? | The list of candidates |
Because the width attribute is not a display width, it does not influence which srcset candidate is chosen when sizes is present. The browser uses sizes for that. If sizes is absent and srcset uses w descriptors, the browser assumes 100vw.
Using attributes with `picture`
Place width and height on the img inside picture. The source elements also accept them in current browsers, but the img is where the attributes are required for broad support, and it is the element that renders the image.
For format switching, all sources share one shape, so one pair of attributes is enough.
<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>Art direction is different. The crops have different ratios, so a single pair on the img is wrong for at least one of them. Look at the example from the earlier chapter.
<picture>
<source media="(min-width: 50em)" srcset="hero-wide.jpg">
<img src="hero-narrow.jpg" width="800" height="800" alt="A sailor looking out to sea">
</picture>Here the img says 800 by 800, a square. When the wide crop is chosen, say at 1600 by 900, the browser first reserves a square box using the img attributes. It then loads the wide file, and the box changes to 16:9. That is a layout shift.
Two fixes exist:
- Put
widthandheighton eachsourcethat has a different ratio. Browsers that support this use the matching values for the reserved box. - Set the ratio in CSS with media queries that mirror the
sourceconditions.
<picture>
<source media="(min-width: 50em)" srcset="hero-wide.jpg" width="1600" height="900">
<img src="hero-narrow.jpg" width="800" height="800" alt="A sailor looking out to sea">
</picture>.hero img { max-width: 100%; height: auto; }If you rely on CSS instead, use the same breakpoint as the media attribute.
.hero img { aspect-ratio: 1 / 1; width: 100%; height: auto; }
@media (min-width: 50em) {
.hero img { aspect-ratio: 16 / 9; }
}The CSS aspect-ratio value overrides the ratio derived from the attributes. If the file's real ratio then differs from the CSS value, the image is cropped or stretched according to object-fit, so keep the two consistent.
Common mistakes
- Leaving out the attributes. The most frequent cause of image-related layout shift.
- Writing units.
width="400px"is invalid, and browsers may ignore it. - Setting
heightin CSS to a fixed value while allowingwidthto shrink. The image distorts. Useheight: auto. - Using
height: autoand expecting it to work with no attributes. It will, but only after the file loads, so the shift remains. - Using attribute values that do not match the file ratio. The reserved box then differs from the final image, and the shift is merely smaller.
- Using different ratios across
srcsetcandidates. The box changes whenever the browser swaps files, for example after a window resize.
Lazy loading depends on this
Deferred images, covered in a later chapter, rely on reserved space. When loading="lazy" delays a file, the box must already exist. Without dimensions, a lazy image occupies no space, so the browser may believe many images are near the viewport at once and load them all. With dimensions, the boxes have correct heights and only the nearby ones load.
Exercise
A page has <img src="a.jpg" width="1200" height="800" alt="Boats"> and the CSS rule img { max-width: 100%; height: auto; }. The container is 300 CSS pixels wide. What height does the browser reserve before the file loads, and what would go wrong if the rule were img { max-width: 100%; height: 800px; }?
Show answer
The browser reserves 200 pixels of height. The ratio is 1200:800, which is 3:2, and 300 divided by 1.5 is 200. With a fixed height: 800px, the box would be 300 pixels wide and 800 pixels tall, so the image would be badly distorted (or cropped with object-fit) and would leave a large empty area.
Exercise
You use picture with a square crop (800 by 800) for narrow screens and a 1600 by 900 crop for viewports of at least 50em. Only the img has width="800" height="800". What happens on a wide screen, and how do you fix it without CSS?
Show answer
The browser reserves a square box from the img attributes, then the 16:9 file loads and the box changes shape, which shifts the content below. Add width="1600" height="900" to the source element with the min-width: 50em condition so the reserved box matches the wide crop.