Aspect ratio utility
Lock any element to a precise aspect ratio using the native CSS aspect-ratio property — no padding hacks needed.
Square
Widescreen
Classic
Quick implementation
.ratio-1-1 {
aspect-ratio: 1;
width: 100%;
display: grid;
place-items: center;
}
.ratio-16-9 {
aspect-ratio: 16/9;
width: 100%;
display: grid;
place-items: center;
}
.ratio-4-3 {
aspect-ratio: 4/3;
width: 100%;
display: grid;
place-items: center;
}
Prompt this to your LLM
Includes role, constraints, two framework variants, and edge cases to handle.
You are a senior frontend engineer writing a CSS layout utility library.
Goal: Create utility classes that lock elements to common aspect ratios using the CSS aspect-ratio property.
Technical constraints:
- Use aspect-ratio with a ratio value (e.g. 16/9, 4/3, 1) — not the old padding-top hack.
- Set width: 100% so the element fills its container horizontally and height is derived from the ratio.
- Include display: grid; place-items: center so content is centered inside each box.
- Use oklch() for any demo colors, not hex or rgba().
- Generate utilities for: 1:1 (square), 16:9 (widescreen), 4:3 (classic), 3:2 (photo), 9:16 (portrait).
Framework variant (pick one):
A) Vanilla CSS utility classes .ratio-1-1, .ratio-16-9, .ratio-4-3, .ratio-3-2, .ratio-9-16.
B) React component — accepts ratio prop as a string like "16/9" and renders children inside.
Edge cases to handle:
- If content is taller than the ratio allows, it overflows — add overflow: hidden or min-height: 0 to control it.
- Works on replaced elements (img, video, iframe) with object-fit: cover to fill the box.
- If both width and height are explicitly set, aspect-ratio is ignored — document this.
Return CSS.
Why this matters in 2026
Before aspect-ratio, maintaining responsive boxes required the notorious padding-top percentage hack — setting padding-top: 56.25% for a 16:9 box and positioning content absolutely inside it. The native aspect-ratio property replaced all of that with a single declaration. It is now universally supported and works on any element including <img>, <video>, and <iframe>.
The logic
The browser resolves aspect-ratio after computing the element's width. It then derives the height automatically from the ratio. For a width: 100% element in a 300px container, aspect-ratio: 16/9 produces a height of 300 × 9/16 = 168.75px — always proportional, always responsive.
When paired with display: grid; place-items: center, the ratio box also acts as a centered layout container — suitable for thumbnails, video embeds, and icon containers that must stay geometrically consistent across viewport sizes.
Accessibility & performance
Using aspect-ratio on <img> and <video> elements is recommended by browsers for layout stability: when the browser knows the dimensions in advance, it reserves the correct amount of space before the media loads, preventing Cumulative Layout Shift (CLS). This is one of the few CSS properties that directly improves Core Web Vitals scores.