CodeBlanks Logo Icon CodeBlanks

Aspect ratio

HTML course · Advanced · Lesson 10/56

Preserve ratio with CSS aspect-ratio and width/height.

Intrinsic size

Writing width and height attributes on an <img> tells the browser its intrinsic size. With these known up front, the browser can reserve space on the page before the image loads.

Without reserved space, the image pushes content down once it loads, causing a layout shift. That shift hurts the user experience and the CLS (Cumulative Layout Shift) score. So width/height is not just decoration; it is a performance measure.

CSS aspect-ratio

The aspect-ratio CSS property locks a box's ratio. For instance, aspect-ratio: 16 / 9 keeps the height at a 16:9 ratio no matter the width. You can apply it to an <img>.

Still, writing width and height in HTML is usually better: the browser computes the ratio itself and reserves space before the image loads. CSS aspect-ratio keeps only the ratio, not the size, so using both together is safest.

Exercise Write picture, source and img (with width/height)

Add a <picture> to body. Inside it put a <source> with media set to (min-width: 800px) and srcset set to gallery-wide.jpg. Then add an <img> with src set to gallery-narrow.jpg, alt set to Gallery, width set to 800 and height set to 450.

Show example solution
<body>
  <picture>
    <source media="(min-width: 800px)" srcset="gallery-wide.jpg">
    <img src="gallery-narrow.jpg" alt="Gallery" width="800" height="450">
  </picture>
</body>

Test yourself

  1. What is the main benefit of writing width and height on <img>?

    • No CSS is needed to resize the image
    • The browser reserves space, reducing layout shift while loading
    • It generates the alt text automatically
    • It sets the image format (AVIF/WebP)
    Show answer

    The browser reserves space, reducing layout shift while loading — Correct. width/height lets the browser reserve space, which reduces CLS.

  2. Write the CSS aspect-ratio

    <style>
      .hero {
        width: 100%;
        ____: 16 / 9;
      }
    </style>
    Show answer
    <style>
      .hero {
        width: 100%;
        aspect-ratio: 16 / 9;
      }
    </style>
  3. Match each ratio to its use

    16 / 9
    Cinema screen ratio
    4 / 3
    Old TV ratio
    1 / 1
    Square image
    21 / 9
    Cinema scope ratio

All lessons in Advanced