Basic

Images: size, format, and dimensions

An image costs bytes times the number of times it is requested, and it also costs layout if the browser does not know its size. Both are fixed in the same place: the file on disk and the attributes in the tag.

What you will see

A decorative image with a reserved box and no announcement.

About 1 min of reading

Try It

Fix the two numbers for one image

1

Find images without dimensions

grep -oE ']*>' index.html | grep -vE 'width=|height=' | wc -l

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Zero. Each hit is an image that will cause a layout shift.
2

Check the file size

ls -la public/images/ | sort -k5 -n | tail -5

Before you run it, say out loud what it will print. Then open the answer.

What it prints
The five largest files. Any that display small are oversized on disk.
3

Resize on disk

identify public/images/*.png 2>/dev/null | head -5 || file public/images/*.png | head -5

Before you run it, say out loud what it will print. Then open the answer.

What it prints
The pixel dimensions of each file, compared against the box it is displayed in.
4

Add the attributes

printf '\n' | tee -a index.html

Before you run it, say out loud what it will print. Then open the answer.

What it prints
A decorative image with a reserved box and no announcement.
Do not set only one of width or height. The browser needs the ratio before the bytes arrive, and one number alone does not always give it.

Data Flow

Image file to painted box
1 Decode the file to pixels
↓
2 Scale to the CSS box
↓
3 Reserve the box from width and height
↓
4 Paint without reflowing siblings
Why this works
The two numbers per image

Bytes on disk and the display box. If the ratio of pixels to box is far above one, the file is oversized and the fix is on disk.

Where alt and size interact

A decorative image needs alt="" and dimensions both. The alt stops the announcement and the dimensions stop the reflow; neither one implies the other.

Examples

Width and height always

An img with no width or height has no aspect ratio, so the browser reflows everything below it once the image arrives. That reflow is a layout shift, and it is measurable.

Format by content

A photo is a raster format. A flat diagram or an icon is often smaller as a vector, and a vector scales without a second file. Choose by what the image is, not by what the tool defaults to.

Serve the size you use

A 2000 pixel image displayed at 400 costs five times the bytes it needs. Resize on disk at build time rather than at runtime, so the cost is paid once.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Cache headers and the token
Previous Lesson
Cache headers and the token
Next Lesson
Fonts and the text that shifts
Fonts and the text that shifts →