CSS aspect-ratio
Enforce width-to-height ratios for responsive media containers and UI elements using the modern aspect-ratio property.
Overview
Key Points
- •aspect-ratio: 16 / 9 maintains widescreen ratio (divide to check: 16/9 ≈ 1.78)
- •aspect-ratio: 1 creates a perfect square regardless of width
- •If both width and height are set explicitly, aspect-ratio is ignored
- •Combine with width: 100% for responsive containers that maintain ratio
- •Use with object-fit: cover on img children for responsive media
- •Works on any element, not just media great for icon boxes and ratio-locked cards
- •Replaces the old padding-top percentage hack completely
Examples
Responsive video embed container
.video-container {
width: 100%;
aspect-ratio: 16 / 9;
background: #000;
border-radius: 12px;
overflow: hidden;
}
.video-container iframe,
.video-container video {
width: 100%;
height: 100%;
display: block;
}As the container grows/shrinks in width, the height automatically adjusts to maintain 16:9.
Consistent image cards with aspect-ratio + object-fit
.card-image {
width: 100%;
aspect-ratio: 3 / 2; /* landscape photo ratio */
object-fit: cover;
display: block;
border-radius: 12px 12px 0 0;
}
/* Square thumbnail */
.thumbnail {
width: 80px;
aspect-ratio: 1;
object-fit: cover;
border-radius: 8px;
}No need to set height explicitly aspect-ratio computes it from the width.
Icon box that stays square
.icon-box {
width: 48px;
aspect-ratio: 1;
background: #eef2ff;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.25rem;
flex-shrink: 0; /* prevent flex shrinking */
}Common Mistakes
- Setting both width and height explicitly this overrides aspect-ratio; only set one dimension
- Using aspect-ratio without object-fit: cover on img tags the image inside may distort
- Expecting aspect-ratio on flex/grid items to work when the container forces a specific height explicit container height takes precedence
Note
aspect-ratio is perfect for skeleton loaders and placeholder elements set the expected ratio on the container before content loads to prevent layout shifts. This contributes to better CLS (Cumulative Layout Shift) Core Web Vitals scores.
Exercises
Write CSS to style the HTML scaffold. The preview updates live — when it looks right, mark as done.
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4