Aspect ratio, on any element

Photo of aspect ratio grid
So you have all the information in your backend: height and width of the original image and therefore the aspect ratio, why not just inline style the image dimensions in the template layer?

Yeah sure, that would work, if you don't need to resize based on media queries. Oh, and it would not play well with our habit of sizing elements in rems so that we could either scale them with the font size of the root element or they scale along if someone has a higher font size set up in their browser for accessibility reasons.

For the curious: check out the results at gilbert-lodge.com.

So we came up with the idea to encode the aspect ratio into the markup via the backend. That way we could still control the size of elements via CSS. First, we had to get the aspect ratio from the backend into the markup. As we have twig templates, this can be achieved with some inline maths expression, dividing width by height and resulting in following the markup:

<div class="portfolio__item" style="width: 1.333em">
<!-- width could be any aspect ratio calculated in the backend -->
<img href="/static/foo.png" >
</div>

An image of proportions 4 by 3 has an aspect ratio of 1.333... if we want to style the parent of the image to a height of 80px and have the width play along accordingly we just have to set the font-size property to the same value as we set height. Basically using the font size as a variable to pass height as value which then gets multiplied by the width in ems and results in the expected width. It's a bingo!

.portfolio__item {
font-size: 80px;
height: 80px;
}

@media (min-width: 1000px) {
.portfolio__item {
font-size: 160px;
height: 160px;
}
}

Closing

Obviously, this a hack, as examining CSS or HTML on their own will never reveal the inner workings and therefor this technique might be called a bit obscure. But Projects with a large collections images with different aspect ratios that need to be of the same height, in my opinion a viable solution. One might be tempted to try to use font size as a alternative to a lacking variable (for the moment) in CSS. I highly encourage that.