← All writing
Craft · · 2 min

aspect-ratio

One property, and the only gotcha is what happens when the content inside refuses to fit.

CSS Images Small Print

For about a decade the way to hold a 16:9 box was a wrapper with padding-top: 56.25% and an absolutely positioned child, plus a comment explaining the number to whoever came next.

ratio.css
.video {
  aspect-ratio: 16 / 9;
}
CSS

That is the replacement. It has been safe to use for long enough that I no longer check.

It earns the most not on video embeds but on images with a srcset. width and height attributes already give the browser a ratio to reserve space with, but the moment CSS sets width: 100% and height: auto on responsive images (which nearly every stylesheet does), you want the ratio expressed in CSS too or the reservation goes away.

ratio.css
img {
  height: auto;
  max-width: 100%;
  aspect-ratio: attr(width) / attr(height);
}
CSS

That attr() form needs checking before you lean on it; the safe version is to set the ratio per component and it works everywhere.

The gotcha: aspect-ratio is a suggestion, not a cage. If the content inside is taller than the ratio allows, the box grows and the ratio is ignored, because the alternative is overflow. That is nearly always what you want and it is confusing exactly once, when a card with a long heading in it comes out taller than its siblings and the property looks broken.

min-height: 0 on the child is usually the thing that lets it hold.

Read similar posts
2 min

light-dark()

Two color values in one declaration, picked by the color scheme, which removes most of the reason a theme needed a second block of custom properties at all.

2 min

scrollbar-gutter

The layout shifts by fifteen pixels when a modal opens, everybody blames the modal, and the actual cause is the scrollbar disappearing along with it.