Sub topic 10
Width, height, and lazy loading
This chapter assumes you can write an img element with src and alt, and that you know how HTML attributes work. You should also be comfortable opening a local HTML file in a browser. Here you will learn why image dimensions matter for page stability and how loading="lazy" changes when images download.
The problem: layout shift
A browser reads HTML from top to bottom. When it reaches an img, it usually does not know how large the image is until the file has started to download. If the markup gives no size, the browser reserves no space. It lays out the text below the image as if the image were 0 pixels tall. When the image arrives, the browser makes room for it and pushes everything below it down.
This jump is called layout shift. It is annoying to readers. A reader who is halfway through a sentence sees the text move, or taps a button that has just moved away. Search engines also measure it. Google's Cumulative Layout Shift (CLS) metric scores how much visible content moves during loading.
The fix is to tell the browser the image's size in the HTML, so it can reserve the right amount of space before any image data arrives.
The width and height attributes
The width and height attributes on img take whole numbers. They are measured in CSS pixels and written without a unit.
<img src="images/red-fox.jpg" alt="A red fox standing in snow" width="640" height="427" loading="lazy">Write width="640", not width="640px". A value with a unit is invalid in HTML and may be ignored.
The values should describe the image's intrinsic size, which is the pixel size of the file itself. Use the real numbers. You can read them from your image editor or your operating system's file properties.
How the browser uses them
Modern browsers use the two attributes to work out the image's aspect ratio. That is the ratio of width to height, here 640:427. The browser reserves a box with that ratio before the file loads.
This works even when CSS resizes the image. A common rule in a responsive site is:
img {
max-width: 100%;
height: auto;
}With this rule, the displayed width shrinks to fit the container. height: auto tells the browser to compute the height from the aspect ratio. Because width and height in the HTML supplied that ratio, the space is still reserved correctly. Without the attributes, height: auto collapses to 0 until the file arrives.
Display size versus intrinsic size
The attributes do not have to equal the displayed size. A 1600 by 900 file can be shown at 800 pixels wide. What matters is that the ratio is correct. If you set width="1600" height="900" and CSS sets the displayed width to 800 pixels, the browser computes a height of 450 pixels.
A wrong ratio causes problems of its own. If the attributes say 4:3 but the file is 16:9, the browser reserves a 4:3 box. When the file loads, the box snaps to the real shape and the layout shifts anyway. If CSS forces both dimensions, the image is stretched.
Setting dimensions in CSS instead
You can also reserve space with the CSS aspect-ratio property.
.hero {
aspect-ratio: 16 / 9;
width: 100%;
height: auto;
}This is useful when you do not control the HTML, for example with content from a CMS. For images you write yourself, the HTML attributes are the simplest option and work in every browser that supports aspect-ratio mapping from attributes.
Lazy loading
By default, a browser downloads every image it finds in the HTML, even for images far below the visible area. On a long page with many photos, this wastes bandwidth and slows the content the reader actually sees.
The loading attribute changes this. It accepts two values:
| Value | Behavior |
|---|---|
| `eager` | Load immediately. This is the default. |
| `lazy` | Delay loading until the image is near the visible area. |
<img src="images/gallery-12.jpg" alt="Harbor at low tide" width="800" height="600" loading="lazy">The browser decides what "near" means. Chrome, for example, starts loading an image a certain distance before it scrolls into view, so it is usually ready when the reader arrives. That distance varies by browser and connection speed.
Lazy loading depends on dimensions
Lazy loading and width/height belong together. A lazy image has not loaded when the page is first laid out. Without reserved space, every image would be 0 pixels tall. The browser might then decide that all the images are in view, because they take no room, and load them all at once. Setting dimensions keeps the page the right height, so the browser can tell which images are off screen.
Do not lazy-load the main image
Do not put loading="lazy" on images that appear at the top of the page, such as a hero banner or the first photo in an article. These images are probably the largest visible element, which Google's Largest Contentful Paint (LCP) metric measures. Delaying them makes the page feel slower. Leave them at the default eager, or write loading="eager" to be explicit.
A practical rule: images visible without scrolling load eagerly, and images below the first screen load lazily. Screen sizes differ, so you cannot know exactly where the fold is. When unsure, treat the first one or two images as eager.
Edge cases
- Images in a hidden tab or collapsed section. The browser generally defers lazy images that are not rendered, and loads them when they become visible. This is usually what you want.
- Printing. Lazy images that have not loaded may be missing from printouts in some browsers. If printing matters, consider eager loading for key images.
- Unsupported browsers. A browser that does not know
loadingignores it and loads the image normally. The page still works. pictureandsrcset. Putloadingand the size attributes on the innerimg, not onsource. Theimgis the element that controls loading.
Putting it together
This page has one eager hero image and several lazy gallery images, each with dimensions.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Coastal walks</title>
<style>
img { max-width: 100%; height: auto; }
</style>
</head>
<body>
<h1>Coastal walks</h1>
<img src="images/cliffs.jpg" alt="Chalk cliffs above a pebble beach" width="1200" height="675">
<h2>Gallery</h2>
<img src="images/harbor.jpg" alt="Fishing boats resting in a harbor at low tide" width="800" height="600" loading="lazy">
<img src="images/lighthouse.jpg" alt="White lighthouse on a grassy headland" width="800" height="600" loading="lazy">
<img src="images/dunes.jpg" alt="Sand dunes with tall grass at sunset" width="800" height="600" loading="lazy">
</body>
</html>To see the effect, replace the file names with real images, open the page, and use your browser's developer tools. In the Network tab, reload the page and watch the gallery images load only as you scroll.
Common errors
- Adding units, as in
width="640px". Use plain numbers. - Entering the wrong aspect ratio, which causes a shift when the image loads.
- Leaving out
height: autoin CSS whenmax-width: 100%is set. The image can then be squashed, because the HTMLheightis still applied. - Lazy-loading the top image of the page.
- Treating lazy loading as a replacement for compressing images. A lazy 5 MB photo is still 5 MB when it loads.
Exercise
A page has a banner image at the top and ten photos further down. The banner file is 1200 by 400 pixels. Write the img element for the banner, then explain which loading value the photos should use and why they need width and height as well.
Show answer
Banner: <img src="images/banner.jpg" alt="Description of the banner" width="1200" height="400">. It has no loading="lazy" because it is visible at once and delaying it would slow the largest visible element. The photos should use loading="lazy" so they download only when the reader scrolls near them. They still need width and height so the browser reserves space for each one. That prevents layout shift and lets the browser tell which images are off screen.
Exercise
An image file is 1600 by 900 pixels. A developer writes width="1600px" height="900px". What is wrong, and what is the corrected markup?
Show answer
HTML dimension attributes take whole numbers without units, so the px suffix is invalid. The corrected attributes are width="1600" height="900".