Minimum aspect ratio in CSS
Posted on in WebThe padding-bottom
aspect ratio trick has been around for a while, and until we get the official unit, it’s all we’ve got to create fluid-sized elements. At Daisie, I remember needing a ‘minimum aspect ratio’ but never properly implemented it. Today, when working on some cards, that requirement came up again.
The aim is to have a container at a minimum aspect ratio, but if the content within exceeds it, we allow it to grow.
The result
The code
The CSS is nice and succinct, and straight out of 2012. Clearfixes n' all. The :before
pseudo element uses the padding-bottom
trick to give the container some height, but floats out the way, and the :after
clears up afterwards. If the content is larger than the box, the element is defined by that height instead.
.min-aspect:before {
padding-bottom: 50%; /* Minimum aspect ratio */
content: '';
float: left;
}
.min-aspect:after {
display: table;
content: '';
clear: both;
}
The addition
This can also be bolstered with min-height
on the parent, giving you three axis of control!
The caveat: Given how classicâ„¢ this code is, this has probably been implemented many times before, but my googling skills weren’t good enough to find other articles on the matter.
Posted on in Web