Images and media

Image dimensions and loading

Reserve the right amount of space for an image and defer off-screen images without causing the page to jump while it loads.

Tell the browser an image’s intrinsic dimensions so it can reserve space before the file finishes downloading:

<img
  src="bicycle.jpg"
  alt="A red bicycle parked beside a canal"
  width="1200"
  height="800"
>

The values are unitless pixel dimensions of the source image. They give the browser an aspect ratio early, even on a slow connection.

Without width and height, the page renders with a gap where the image will appear. When the file arrives, everything below it jumps down. That shift is annoying on desktop and worse on mobile where people tap links that move under their finger.

CSS can still display the image at a different size on screen. The attributes describe the source file and reserve the right shape. CSS controls the layout.

Images below the first screen can use native lazy loading:

<img
  src="gallery-12.jpg"
  alt="Cyclists crossing the harbor bridge"
  width="1200"
  height="800"
  loading="lazy"
>

The browser delays the request until the image is near the viewport. That saves bandwidth on long pages.

Do not lazy-load the hero image at the top of the page. Delaying the first visible image can make the page feel slower, not faster.

A common mistake is setting width in CSS but omitting both attributes in HTML. The layout still jumps because the browser had no aspect ratio at parse time. Add width and height in HTML, then scale with CSS.

When you add photos to your my-page project, include width, height, and alt on every informative image. Reload on a throttled connection in DevTools and watch whether content below stays stable as images arrive.

Compare the same page once with width and height removed. The jump when images load is the failure mode you are preventing.

Quick check

Result

You got of right.

Lesson completed