Do you ever wondered how to scale a div within a fluid layout, keeping its aspect ratio?
The solution is pretty easy, and – amazingly – you don’t need Javascript!
Just nest your element in a fluid container – this will be our ratio-killer – and give it these rules:
.container { position: relative; display: inline-block; width: 50%;
}
These properties will let our container div to scale accordingly to the parent element width. Then, we’ll use CSS3 pseudo elements on the container to do the magic:
&:before {
content: "";
display: block;
padding-top: 145%;
}
The padding-top will represent the height of our div. So tweak the percentage accordingly to the desired aspect ratio!
Finally, we’ll place the element for the contents and give it absolute positioning:
.inside-content {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
And voilà! The trick is done: we now have a fluid element that scales keeping its aspect ratio.
Want to give it a ride? Here’s an example: http://cdpn.io/GIJmz