For a long time we’ve been told the only way to have a DOM element keep a fixed aspect ratio without Javascript is with the % padding trick. Like here: https://css-tricks.com/aspect-ratio-boxes/

But what if there was a nicer looking hack to do this?

With a combination of CSS grid and SVG, there is.

We use two important attributes:

SVG knows how to maintain aspect ratio

CSS grid knows how to make overlapping items affect each other’s size

So we end up with this:

<style>

.aspectRatioSizer {

display: grid;

} .aspectRatioSizer > * {

grid-area: 1 / 1 / 2 / 2;

}

</style> <div class="aspectRatioSizer">

<svg viewBox="0 0 7 2"></svg>

<div>

Content goes here

</div>

</div>

This, no matter how large the grid is, will maintain an aspect-ratio of 7/2, is pretty easy to read, supported on IE11 (with the old grid syntax) and doesn’t require special hacks.

Here is a codepen:

If anyone finds an even simpler way to do this, or issues, I’d love to hear!

(Of course the padding trick may still seem nicer, a matter of taste…)