Go to homepage

Projects /

August 4, 2020

Aspect Ratio in CSS

By CodyHouse
404 HTML, CSS, JS components. Download →

How to set the aspect ratio in CSS using custom properties.

While we wait for the aspect-ratio property to be supported by more browsers, here's a CSS trick (also known as "the padding hack") to set the aspect ratio of an element!

Here's how it works: set the height of the parent equal to 0, the padding-bottom equal to (height/width)*100% of the desired ratio. The child should be in absolute position and inherit the size of the parent. Finally, we add object-fit "cover" to prevent image distortion. Use a custom property to make the ratio easy to customize.

HTML:

<div class="custom-aspect-ratio">
  <img src="assets/img/img.jpg" alt="Image description">
</div>

CSS:

.custom-aspect-ratio {
  --aspect-ratio: 16/9;
  position: relative;
  height: 0;
  padding-bottom: calc(100%/(var(--aspect-ratio)));
}

.custom-aspect-ratio > * {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

Live demo:

Project duplicated

Project created

Globals imported

There was an error while trying to export your project. Please try again or contact us.