snippetcssTippending
CSS aspect-ratio for responsive media
Viewed 0 times
aspect-ratioresponsiveobject-fit16:9layout shiftcls
Problem
Need to maintain aspect ratios for images, videos, and containers without the old padding-bottom hack.
Solution
Modern aspect-ratio property:
aspect-ratio + object-fit + width: 100% is the modern trifecta for responsive media.
/* Simple aspect ratio */
.video-container {
aspect-ratio: 16 / 9;
width: 100%;
}
.square {
aspect-ratio: 1; /* Same as 1/1 */
width: 200px;
}
/* Responsive image with aspect ratio */
img {
width: 100%;
height: auto;
aspect-ratio: 4 / 3; /* Reserves space before load (prevents CLS) */
object-fit: cover; /* Crop to fit ratio */
}
/* Card with fixed ratio hero image */
.card-image {
aspect-ratio: 2 / 1;
width: 100%;
object-fit: cover;
border-radius: 8px 8px 0 0;
}
/* Responsive iframe (YouTube, maps) */
.embed {
aspect-ratio: 16 / 9;
width: 100%;
}
.embed iframe {
width: 100%;
height: 100%;
border: 0;
}
/* Common aspect ratios */
.widescreen { aspect-ratio: 16 / 9; } /* Video */
.standard { aspect-ratio: 4 / 3; } /* Photos */
.portrait { aspect-ratio: 3 / 4; } /* Portrait photos */
.cinema { aspect-ratio: 21 / 9; } /* Ultra-wide */
.golden { aspect-ratio: 1.618 / 1; } /* Golden ratio */
/* Old padding hack (no longer needed)
.old-way {
position: relative;
padding-bottom: 56.25%; /* 16:9 = 9/16 = 0.5625 */
}
.old-way > * {
position: absolute;
inset: 0;
}
*/aspect-ratio + object-fit + width: 100% is the modern trifecta for responsive media.
Why
aspect-ratio eliminates the padding-bottom hack, prevents Cumulative Layout Shift by reserving space, and makes responsive containers trivial.
Context
Responsive images, videos, and containers in CSS
Revisions (0)
No revisions yet.