Easily preserve any aspect ratio with pure CSS

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>

Published


You might enjoy these as well

  1. Easy Typewriter effect/animation with Javascript
  2. React/Preact hook: usePersistedStore
  3. React/Preact hook: useEventListener
  4. Using Styled components with Preact
  5. Load a specific image depending on light/dark mode
  6. Using Angular CLI with Laravel
  7. Deploy to Netlify via GitHub actions and "$ave Dat Money"
  8. Easy Light and Dark mode switching with CSS