CSSeasyCSS

Aspect Ratio Container

Maintain consistent aspect ratio for images, videos, or containers.

01

The problem

You need containers or media elements to maintain a consistent aspect ratio across different screen sizes.

02

The solution

CSS
/* Modern aspect-ratio property */
.ratio-16-9 {
  aspect-ratio: 16 / 9;
  width: 100%;
  object-fit: cover;
}

.ratio-4-3 {
  aspect-ratio: 4 / 3;
}

.ratio-1-1 {
  aspect-ratio: 1 / 1; /* Square */
}

/* For images */
.responsive-img {
  width: 100%;
  height: auto;
  aspect-ratio: 16 / 9;
  object-fit: cover;
  border-radius: 8px;
}

/* Legacy padding-bottom trick */
.ratio-box-legacy {
  position: relative;
  width: 100%;
  padding-bottom: 56.25%; /* 16:9 = 9/16 = 0.5625 */
}

.ratio-box-legacy > * {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

03

See it live

Isolated previewSandboxed
04

Put it to work

Example
<div class="ratio-16-9">
  <img src="thumbnail.jpg" alt="Video thumbnail">
</div>

<video class="ratio-16-9" controls>
  <source src="video.mp4" type="video/mp4">
</video>

Worth knowing

The aspect-ratio property is widely supported. Use the padding-bottom trick only for older browser support.