CSS Aspect Ratio Boxes
Maintain consistent aspect ratios for media containers using CSS aspect-ratio property without padding hacks.
Code
.video {
aspect-ratio: 16 / 9;
width: 100%;
}
.square {
aspect-ratio: 1;
}
.portrait {
aspect-ratio: 3 / 4;
}CSS Aspect Ratio Boxes
Maintain consistent aspect ratios for media containers using CSS aspect-ratio property without padding hacks.
Code
.video {
aspect-ratio: 16 / 9;
width: 100%;
}
.square {
aspect-ratio: 1;
}
.portrait {
aspect-ratio: 3 / 4;
}
Explanation
Each box keeps its ratio as the width flexes: a 16 / 9 video, a 1 square, and a 3 / 4 portrait. Expected behavior: the height is derived from the width, so the element no longer needs a padding-top percentage hack. Limitation: an explicit height or a replaced element’s own intrinsic size can override the declared ratio.
Interactive Tools for This Topic
Aspect Ratio CalculatorSimplify a width-to-height ratio, show its decimal value, and derive a matching height for a new width.CSS Flexbox PlaygroundInteractively test CSS flexbox container and item properties with a live preview. Adjust justify-content, align-items, flex-direction, and flex-grow to see layout changes.CSS Grid PlaygroundExperiment with CSS grid layout properties interactively. Define columns, rows, gaps, and areas while watching the grid template update in a live visual preview.Border Radius PreviewPreview four-corner border-radius values on a live box and copy the generated shorthand border-radius CSS declaration.
Report a problem with this exampleOpens a pre-filled issue on GitHub.