Prevent layout shift with image width and height in HTML
4 An image that does not shift the page
easyPlace two images: one that carries information and one that is pure decoration. Reserve their space so nothing jumps as they load, and let them shrink on a narrow screen.
Stuck? Three hints, smallest first
- 1.
widthandheightattributes let the browser reserve the box before the bytes arrive. - 2. A decorative image takes
alt=""— empty, never missing. Missing means the reader hears the filename. - 3.
max-width: 100%withheight: autolets it shrink and keeps the ratio.
<img
class="shot"
width="240" height="150"
alt="Six bays under a corrugated roof, each with a bus reversed into it"
src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='240' height='150'%3E%3Crect width='240' height='150' fill='%233055d8'/%3E%3Crect y='96' width='240' height='54' fill='%230b3a8f'/%3E%3C/svg%3E">
<img
class="rule"
width="240" height="8"
alt=""
src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='240' height='8'%3E%3Crect width='240' height='8' fill='%23ffd75e'/%3E%3C/svg%3E">
img {
display: block; /* removes the few pixels of gap an inline image leaves */
max-width: 100%; /* never wider than the column */
height: auto; /* so the aspect ratio survives the shrink */
border-radius: 6px;
}
.rule {
margin-top: 10px;
border-radius: 2px;
}
8 checks that prove this answer
Assertions, run in the browser. The markup and styles above are handed to them
as html and css, so press Run and each check prints
ok. The build fails if a single one fails.
test('two images', countTag(html, 'img'), 2);
test('the informative one has real alternative text', /alt="[^"]{10,}"/.test(html), true);
test('the decorative one has an EMPTY alt, not a missing one', /alt=""/.test(html), true);
test('both declare their intrinsic size', (html.match(/width="\d+"/g) || []).length, 2);
test('and their height too, so the box is reserved', (html.match(/height="\d+"/g) || []).length, 2);
test('both sources are inline, so nothing is fetched', (html.match(/src="data:image/g) || []).length, 2);
test('they shrink with the column', /max-width\s*:\s*100%/.test(css), true);
test('height auto keeps the ratio while shrinking', /height\s*:\s*auto/.test(css), true);
Output
The width and height attributes look redundant next to CSS, and they are not: the browser divides them to get an aspect ratio and reserves that box before a single byte of image arrives, which is what stops the text below jumping down. Leave them off and you get layout shift on every slow connection. The empty alt="" is the other half — it tells a screen reader “skip this, it says nothing”, whereas no alt at all makes it read the file name out.