Aspect Ratio Box Responsive Media

Maintain a fixed aspect ratio for responsive media containers using the CSS aspect-ratio property without padding hacks.

CssData Fetching

Code

csssnippet
23 lines
.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

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.