How to Set CSS Aspect Ratio on Any Element
The CSS aspect-ratio property maintains an element's proportions regardless of its width. Set aspect-ratio: 16 / 9 and the element is always 16:9 โ whether it's 300px wide or 1200px wide. It replaces the decades-old padding-bottom percentage hack with a single, readable property.
- Use the CSS aspect-ratio property for responsive videos, images, and containers.
- The aspect-ratio Property.
- Covers replacing the padding-bottom hack.
- Covers preventing layout shift with images.
- Covers common aspect ratios.
The aspect-ratio Property
The syntax is straightforward:
.video-container {
aspect-ratio: 16 / 9;
width: 100%;
}
.square-card {
aspect-ratio: 1 / 1;
width: 300px;
}
The element calculates its height automatically from the width and ratio. If both width and height are set, aspect-ratio is ignored โ explicit dimensions take priority.
Replacing the Padding-Bottom Hack
Before aspect-ratio, developers used padding-bottom percentages to maintain ratios:
gap instead of margin hacks for flexbox spacing. It keeps layout code cleaner and is supported in all modern browsers./* Old way */
.video-wrapper { position: relative; padding-bottom: 56.25%; height: 0; }
.video-wrapper iframe { position: absolute; inset: 0; width: 100%; height: 100%; }
/* New way */
.video-wrapper { aspect-ratio: 16 / 9; }
.video-wrapper iframe { width: 100%; height: 100%; }
The new way is cleaner, more readable, and doesn't require absolute positioning tricks.
Preventing Layout Shift with Images
Set width and height attributes on images plus CSS for responsive behavior:
width, height, top, or left. These trigger layout recalculations on every frame and can drop performance below 60fps.img { width: 100%; height: auto; aspect-ratio: attr(width) / attr(height); }
Or use the aspect-ratio property directly: img { aspect-ratio: 4 / 3; object-fit: cover; }. This reserves the correct space before the image loads, preventing cumulative layout shift (CLS) โ a Core Web Vital metric. The CSS Aspect Ratio tool generates the correct values for any dimensions.
Common Aspect Ratios
16:9 โ video, YouTube embeds, widescreen displays. 4:3 โ traditional TV, iPad. 1:1 โ Instagram posts, avatars, product thumbnails. 9:16 โ vertical video (Stories, Reels). 21:9 โ ultrawide/cinematic. 3:2 โ DSLR photos. 4:5 โ Instagram portrait. Use the calculator to find the ratio for any pixel dimensions.