CSS aspect-ratio property

The aspect-ratio property in CSS offers a powerful way to control the proportional dimensions of an element, ensuring consistent aspect ratios regardless of screen size or device. This can be incredibly useful for various web design scenarios, from maintaining image and video dimensions to creating responsive layouts with fixed aspect ratios.

What is aspect ratio?

The aspect ratio of an element describes the proportional relationship between its width and its height. Two common video aspect ratios are 4:3 (the universal video format of the 20th century), and 16:9 (universal for HD television and European digital television, and default for YouTube videos).

Understanding the aspect-ratio property

The aspect-ratio property accepts two types of values:

Here’s the basic syntax:

element {
  aspect-ratio: <ratio> | <keyword>;
}

As of September 2021, the aspect-ratio property is stable in evergreen browsers and is the only property needed to define an aspect ratio.

Examples of using aspect-ratio

Image aspect ratio:

img {
  width: 100%;
  aspect-ratio: 16/9;
  object-fit: cover;
}

This code ensures that the image maintains its 16:9 aspect ratio even when scaled to fit the container width. The object-fit: cover property ensures the entire image is displayed within the container, potentially cropping some parts if necessary.

Creating a square element:

.square {
  width: 200px;
  aspect-ratio: 1;
  background-color: #ccc;
}

This example creates a square element with a width of 200px and a fixed 1:1 aspect ratio, ensuring it remains square regardless of surrounding content.

Aspect ratio gallery:

.gallery {
  --min: 15rem;
  --aspect-ratio: 4/3;
  --gap: 0;
}

.gallery li {
  height: max(25vh, 15rem);
}

@supports (aspect-ratio: 1) {
  .gallery li {
    aspect-ratio: var(--aspect-ratio);
    height: auto;
  }
}

.gallery img {
  display: block;
  object-fit: cover;
  width: 100%;
  height: 100%;
}

By combining it with object-fit and flexbox, we can create a responsive image gallery.

The aspect-ratio property provides a versatile approach to maintaining consistency and responsiveness in your web layouts. By understanding its syntax and exploring various use cases, you can effectively control the dimensions of your elements and enhance the overall user experience.