CSS
Maintain Aspect Ratio with CSS Grid
Create responsive containers that consistently maintain a specific aspect ratio (e.g., 16:9, 1:1) for elements like images or videos using an advanced CSS Grid technique.
.aspect-ratio-box {
display: grid;
overflow: hidden; /* Hides content outside the aspect ratio */
}
.aspect-ratio-box::before {
content: '';
/* Padding-bottom defines the aspect ratio. For 16:9, it's (9/16)*100 = 56.25% */
padding-bottom: 56.25%;
/* Place pseudo-element in the first grid cell */
grid-area: 1 / 1 / 2 / 2;
}
.aspect-ratio-box > * {
/* Place the actual content in the same grid cell, layering it over the pseudo-element */
grid-area: 1 / 1 / 2 / 2;
width: 100%;
height: 100%;
object-fit: cover; /* Useful for images/videos to cover the area */
}
How it works: This powerful CSS Grid technique allows you to maintain a consistent aspect ratio for any container. The parent `.aspect-ratio-box` is set to `display: grid`. A pseudo-element `::before` is used to create the intrinsic height via `padding-bottom`, which is a percentage of the width (e.g., 56.25% for 16:9). Both the pseudo-element and the actual content (`.aspect-ratio-box > *`) are then placed in the exact same grid area (`grid-area: 1 / 1 / 2 / 2`), causing the content to perfectly fill the space defined by the aspect ratio.