Aspect Ratio Box Responsive Media
Maintain a fixed aspect ratio for responsive media containers using the CSS aspect-ratio property without padding hacks.
Code
.video-container {
aspect-ratio: 16 / 9;
width: 100%;
background: #000;
}
.video-container video {
width: 100%;
height: 100%;
object-fit: cover;
}
.square-avatar {
aspect-ratio: 1;
width: 80px;
border-radius: 50%;
overflow: hidden;
}
.poster {
aspect-ratio: 2 / 3;
max-width: 300px;
}Inside the snippet
aspect-ratio pins the box to a fixed width/height ratio, so height follows width with no padding hack.
object-fit decides how the media fills its box while keeping its own aspect ratio.
The rules target .video-container — each selector names the element it restyles, in source order.
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.Box Shadow GeneratorBuild CSS box-shadow values with offset, blur, spread, color, opacity, and inset controls, with a live preview of the result.CSS clamp() GeneratorGenerate responsive clamp(MIN, PREFERRED, MAX) values with automatic calc() wrapping for expressions.Viewport Unit CalculatorConvert between pixels and the CSS viewport units vw, vh, vmin, and vmax for a given viewport size, in either direction.
FAQ
- Which elements does this stylesheet target?
- The rules bind to `.video-container`; when two rules tie in specificity, the one written later in the file wins.
Report a problem with this exampleOpens a pre-filled issue on GitHub.