Aspect Ratio and Responsive Media

Intermediate · 10 min

How aspect-ratio reserves a box's shape, how object-fit crops images into it, and how width, height, srcset and picture keep images sharp without layout shift.

Before thisIntrinsic and Fluid LayoutsSizing Images and Replaced Elements

CSS Weekly · 10 min

Aspect Ratio and Responsive Media

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CSS WeeklyReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `aspect-ratio: 16 / 9` gives a box a height from its width (or the reverse). A `width: 300px` box measured 168.75px tall. It replaces the old padding-top percentage hack.
  • If you set both `width` and `height`, `aspect-ratio` is ignored. And if the content is taller than the ratio allows, the box grows past it unless you set `overflow` to something other than `visible`.
  • `object-fit: cover` crops an image to fill its box, `contain` fits it whole with spare space, and `object-position` chooses which part of a cropped image stays visible.
  • Put `width` and `height` attributes on every `<img>`. Browsers use them to work out the ratio before the file arrives, so the space is reserved and the page does not jump when the image loads.
  • `srcset` with `sizes` lets the browser pick the image file by width and screen density. `<picture>` lets you change the image itself (a different crop) or format at different sizes.

Boxes that know their shape

A responsive layout changes the width of things. If a box’s height comes from its content, that’s fine for text. For media it is not, since an image should keep its proportions and a video should stay 16:9 whatever the container does. Before the browser could do this, people used the “padding hack”: a wrapper with height: 0; padding-top: 56.25% and absolutely positioned content, where the percentage is 9 divided by 16.

aspect-ratio replaces all of that:

.video  { width: 100%; aspect-ratio: 16 / 9; }
.avatar { width: 4rem; aspect-ratio: 1; }          /* 1 = 1 / 1 */

Give the box one dimension and it works out the other. In a browser a width: 300px; aspect-ratio: 16 / 9 box measured 300 by 168.75. It’s Baseline, in every major browser since September 2021.

Where the ratio gives way

It’s a preference, not a lock, and two cases catch people out:

  • You set both dimensions. With width: 300px; height: 50px; aspect-ratio: 16 / 9, the box measured 300 by 50, and the ratio was ignored. Leave one dimension auto.
  • The content doesn’t fit. A 100px-wide aspect-ratio: 1 / 1 box holding a 200px-tall child measured 200px tall, because the default min-height: auto won’t let the box be smaller than its content. The same box with overflow: hidden stayed 100px. Use that only if cropping is acceptable.

object-fit: fitting an image to the box

Once the box has a shape, the image inside needs to fill it without being stretched. An <img> is a replaced element with its own intrinsic ratio, and object-fit says what to do when the box has a different one:

.card img {
  width: 100%;
  aspect-ratio: 4 / 3;
  object-fit: cover;          /* fill the box, crop the overflow */
  object-position: center top; /* keep the top of the photo */
}
  • cover scales the image up until it fills the box and crops what’s left over.
  • contain scales it down until all of it fits, leaving bars.
  • fill (the default) stretches to the box’s shape, which distorts.

With cover, object-position chooses which part survives. The default is the center, which cuts off the tops of heads in portraits.

Reserving space: width and height attributes

A known cause of janky pages is an image loading and pushing everything below it down. The fix is in the HTML:

<img src="hero.jpg" alt="..." width="1200" height="600">

The browser reads the two numbers to work out a 2:1 ratio and reserve that shape before downloading the file. Then your CSS decides the real size:

img { max-width: 100%; height: auto; }

With height: auto, the height follows the width using the ratio from the attributes (and then from the loaded file). This is the standard reset in most stylesheets, and it gives responsive images with no layout shift. The topic of sizing images and replaced elements covers more of why this works.

Choosing the right file: srcset, sizes and picture

CSS controls how big an image is displayed, but a phone shouldn’t download a 3000px file to show a 400px slot. That is solved in HTML:

<img
  src="photo-800.jpg"
  srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
  sizes="(width >= 60rem) 50vw, 100vw"
  alt="..." width="1600" height="900">

srcset lists the files and their widths. sizes tells the browser how wide the image will be shown, so it can choose before layout is done. The browser then picks the smallest file that is sharp enough for the size and the screen’s pixel density.

<picture> is for when the image itself should change, which is called art direction: a wide crop on desktop and a tight crop on a phone, or a modern format with a fallback:

<picture>
  <source media="(width >= 40rem)" srcset="wide.avif" type="image/avif">
  <source media="(width >= 40rem)" srcset="wide.jpg">
  <img src="tall.jpg" alt="..." width="800" height="1000">
</picture>

The <img> inside is required, and it is the element that carries the alt text and the size attributes. srcset and picture have been in every major browser since 2017 and 2016.

What the video covers

CSS Weekly’s “A Practical Guide to Aspect Ratio in CSS” (April 2022, about ten minutes, manual English captions) has these chapters: how the aspect-ratio property works, how the padding hack works, an example with the property, setting aspect ratio on an iframe, what exactly “preferred aspect ratio” means, and how the aspect-ratio media query works. The channel is small, about 13,000 subscribers, and the video is from 2022, but the property hasn’t changed. The video does not cover object-fit, srcset or <picture>, so those sections are the prose’s own, and the two runner-ups cover them: Web Dev Simplified on responsive images and Kevin Powell on object-fit (from 2018). I could not read a transcript, so I do not describe the demos beyond the chapter titles. The measured numbers above come from a browser test.

Where this fits

Replaced elements and intrinsic ratios were introduced in sizing images and replaced elements, and the previous lesson, intrinsic and fluid layouts, covers the container side. The aspect-ratio property also helps grid cards keep their shape as columns change. The final lesson in this group, user preference queries and dark mode, covers media that adapts to the person rather than the screen.

Check yourself

  1. 01A video embed `iframe` collapses to a thin strip at `width: 100%`. How do you give it a 16:9 shape?

    Set `aspect-ratio: 16 / 9` along with `width: 100%` and `height: auto`. An iframe has no intrinsic ratio of its own, so the property supplies one. Previously this needed a wrapper with `padding-top: 56.25%` and absolute positioning.

  2. 02You set `aspect-ratio: 1 / 1` on a card of `width: 100px` with 200px-tall content. How tall is the card?

    200px. The default `min-height: auto` lets content push the box past its ratio, so the ratio is a preference. In a test, the same box with `overflow: hidden` stayed at 100px. Prefer `min-height: 0` or hidden overflow only if clipping is acceptable.

  3. 03A photo is stretched when set to `width: 300px; height: 300px`. What does `object-fit: cover` do, and what is the cost?

    It scales the image to cover the whole box while keeping its proportions, and crops whatever overflows. The photo is no longer distorted, but parts of it are not visible. `object-position` moves the crop, for instance `object-position: top` to keep faces.

  4. 04Why do images need `width` and `height` attributes when CSS sets their size anyway?

    The browser uses the attributes' ratio to reserve space before the file loads, which prevents layout shift. With CSS such as `max-width: 100%; height: auto` the displayed size is still controlled by CSS, but the ratio hint is kept.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark