Easily preserve any aspect ratio with pure CSS

Published on 11 July 2020 1 minute read (19 words)

Thanks to custom properties a.k.a. CSS variables, we can automate aspect ratio preservation without the need for utility classes.

/* Pure CSS */
[style*="--aspect-ratio"] > :first-child {
 width: 100%;
}

[style*="--aspect-ratio"] > img {  
 height: auto;
}

@supports (--custom:property) {
 [style*="--aspect-ratio"] {
  position: relative;
 }

 [style*="--aspect-ratio"]::before {
  content: "";
  display: block;
  padding-bottom: calc(100% / (var(--aspect-ratio)));
 }  

 [style*="--aspect-ratio"] > :first-child {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
 }  
}
// SCSS + Tailwind (fristys.me uses this exact code)
[style*='--aspect-ratio'] {
 @apply relative;

 &::before {
  @apply block;
  content: '';
  padding-bottom: calc(100% / (var(--aspect-ratio)));
 }

 & > :first-child {
  @apply w-full h-full absolute top-0 left-0;
 }

 & > img {
  @apply h-auto;
 }
}
<div style="--aspect-ratio:5/7;">
  <!-- Whatever's here will appear in 5/7 -->
</div>

<div style="--aspect-ratio:16/9;">
  <!-- Whatever's here will appear in 16/9 -->
</div>

<div style="--aspect-ratio:1;">
  <!-- Whatever's here will appear in a square ratio -->
</div>