Entry 02
Image box that holds any upload
Use it on every image, video or embed whose file you do not control, such as thumbnails, cover photos and avatars. The box keeps its shape whatever the file's ratio, and it has that shape before the file loads.
Code
.thumb {
inline-size: 100%;
block-size: auto;
aspect-ratio: 16 / 9;
object-fit: cover;
background-color: var(--surface-muted, oklch(0.9 0 none));
}
.avatar {
flex: none;
inline-size: 3.5rem;
block-size: 3.5rem;
border-radius: 50%;
object-fit: cover;
outline: 1px solid light-dark(oklch(0 0 none / 0.1), oklch(1 0 none / 0.1));
outline-offset: -1px;
}Why it works, the rules and the credits
Why it works
aspect-ratioworks out the height from the width, so the space is there before the file loads.object-fit: coverscales the picture until it fills the box and crops the rest. The default stretches it.- The background color shows until the image paints, and in its place when the load fails.
- An outline with a negative offset draws inside the image's edge. It takes no space and follows the
border-radius, so a white avatar on a white card still has an edge. flex: nonestops the text beside the avatar from squeezing it.
Rules
- One axis must be
auto. Aheightattribute or a fixed height wins over the ratio. The reset setsheight: autoonimg,svgandvideo, andblock-size: autohere does the same for aniframe. object-fitdoes nothing until the box has both sizes or a ratio.covercrops. Usecontainfor logos, product shots and anything that must stay whole. Move the crop withobject-position.- Leave the background color off an image that has transparent areas. It shows through them.
- A fixed-size image in a flex row needs both sizes, as the avatar has. With only a width it stretches to the height of the row.
- In Safari a failed image ignores
aspect-ratioand draws a square box. Where a failed load must not move the layout, put the ratio on a wrapper and give the imageinline-size: 100%andblock-size: 100%. light-dark()needs thecolor-schemefrom One set of color tokens for light and dark. Without it the outline stays black on a dark page.
Support
aspect-ratio in Chrome 88, Firefox 89, Safari 15. An outline that follows the radius in Chrome 94, Firefox 88, Safari 16.4. light-dark() in Chrome 123, Firefox 120, Safari 17.5. The square box of a failed image is from real Safari 27, tested on 2026-10-01. Chrome 150 keeps the ratio.
Credits
Borrowed from: Ahmad Shadeed, Defensive CSS, the tips Image distortion, Image inner border and Default flexbox stretching. This version draws the inner edge with an outline where his adds an element · Heydon Pickering and Andy Bell, The Frame, Every Layout, which wraps the media. On img, video and iframe the rule goes on the element.
Docs: MDN: aspect-ratio · MDN: object-fit · MDN: outline-offset