How to scale a container in an aspect ratio

2016-02-10 | #css, #solution, #webdev

Every once in a while you are tasked with the problem of keeping a container in a certain aspect ratio, no matter the width. If you want to style a nifty little icon container for example. Now, how the hell do I keep an aspect ratio automatically on resize without falling back to JS?

Here's how:

Say you have your icon in a container, which changes its width with the viewport and your container should always be a square based on the width of that container, like this:

<div class="icon-container">

<div class="icon"></div>

</div>

Now you could style your elements like this:

.icon-container {

position: relative;

width: 33.3%;

}

.icon {

padding-bottom: 100%;

background-image: url(logo.svg);

background-repeat: no-repeat;

background-position: center center;

background-size: 100px 100px;

}

So how the hell does this work???

Padding-bottom is not directly linked to a dimension like width and height, although it has a direction. Padding defines to height of an element if nothing else is declared. 100% defaults to width if no dimension is involved. See where this is headed? The width is taken from the first parent with a defined width. So like this, we can dynamically set the height of something based on a percent amount of the parent's width. Using something larger or smaller then 100% now can define you any wished, fixed aspect ratio.