JSRatio - preserving your aspect ratios
1 min read

JSRatio - preserving your aspect ratios

I was trying to do something fun for myself when I ran into the old aspect ratio problem. I wanted a div with a percentage-based width and a height that will update automatically while preserving a certain ratio.

Doing it for an image is really simple, for everything else not so much. While you can do it with only CSS, as seen in this StackOverflow question: How to maintain the aspect ratio of a div using only CSS, it's not neither intuitive, nor easy to use.

The accepted answer requires the use of padding and this affects the flow and the positioning of elements. It also means you have to determine the padding yourself and you cannot simply specify the ratio.

Using Javascript is the safest bet. I mean, you can do pretty much everything with Javascript. However, it's cumbersome to have to use a custom script every time you need such a thing. What if I could do a small library to take care of this for me?

And thus was born JSRatio. A tiny, open source library (here's JSRatio Github's Page), made in less than an hour, JSRatio makes having elements with a fixed ratio easy as pie.

You simply declare the ratio as an attribute (data-js-ratio) on the desired element and that's all.

<div style="width: 50%;" data-js-ratio="1.5"></div>

All it needs is a small initialisation call, preferably near the end of the page and you're good to go.

<script>JSRatio.init();</script>

While it takes care of resizing itself if you play around with the window size, it does comes with an update method, in case the element dimensions are changed dynamically. You can even overwrite the default ratio attribute.

I'm quite happy with the result. While the script itself is no big deal and something that pretty much anyone can code, it's already useful for me and now that it's done I can finally go back to what I initially wanted to do.