Aspect ratio

CSS, Layout · Aug 14, 2022

Creates a responsive container with a specified aspect ratio.

  • Use a CSS custom property, --aspect-ratio to define the desired aspect ratio.
  • Set the container element to position: relative and height: 0, calculating its height using the calc() function and the --aspect-ratio custom property.
  • Set the direct child of the container element to position: absolute and filling it parent, while giving it object-fit: cover to maintain the aspect ratio.
Preview
<div class="container">
  <img src="https://picsum.photos/id/119/800/450" />
</div>
.container {
  --aspect-ratio: 16/9;
  position: relative;
  height: 0;
  padding-bottom: calc(100% / (var(--aspect-ratio)));
}

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

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this