Last Updated: December 26, 2018
·
1.786K
· aebsr

Intrinsic Ratio Less Mixin

In 2009, Thierry Koblentz wrote about Intrinsic Ratios, specifically in regards to videos. By now they're used everywhere, or should be, thanks to RWD. I found myself whipping out a calculator once too often, so I made a simple mixin to do the math for me.

The Mixin

.ir(@width, @ratio) {
    // calculate ratios by dividing width/height
    // so a 16x9 box would be 16/9 = 1.777777778
    width: unit(@width, ~'%');
    height: 0;
    padding-bottom: unit(@width / @ratio, ~'%');
}

.ir(@width, @ratio-width, @ratio-height) {
    .ir(@width, unit(@ratio-width) / unit(@ratio-height));
}

Usage

You can declare your box using only two params if you so choose. Simply, the width at which you want the box to appear and the ratio that it should maintain. There's a lot of flexibility in how you pass your params thanks to @lettertwo and @matthewwithanm.

.ir(16.6667%; 430px; 380px) and .ir(16.6667%, 430/380) generates a box at 430 by 380 that is 1/6 of the offset parent width.

.ir(25%, 1.6) creates an 8 by 5 box that is 1/4 of the offset parent width

.ir(33.3334%, 8, 5) creates an 8 by 5 box that is 1/3 of the offset parent width

.ir(100%, 16/9) creates 16 by 9 box that is 100% of the offset parent width

I've added to my own LESS Toolset where you are welcome to get your fork on.

CSS

Using the first 8x5 example above you end up with this CSS.

width: 25%;
height: 0;
padding-bottom: 15.625%;