How to Keep Your Flexbox Square
UPDATE: There is now an aspect-ratio
CSS property which can be used to set the ratio between width and height. The best way to make a square is now aspect-ratio: 1 / 1
If you remember the days of floats and table layouts, display: flex
is absolutely magical... until you want to make a square.
Flex-box is supremely powerful at creating beautiful spacings, but it does it by overriding the width
and height
properties. This can make it tricky to use old tricks like height: auto
to retain your aspect ratios.
Fortunately, there's a trick to keeping your flex children square, while still allowing them to scale their size up and down.
.parent {
display: flex;
}
.child {
/* flex settings can be basically anything */
flex: 1 0 auto;
height: auto;
}
.child:before {
content: '';
display: block;
padding-top: 100%;
}
That's it. It's super simple.
It works because padding percentage is calculated from the parent's width.
- We allow for
display:flex
to setwidth
however it wants, -
padding-top: 100%
on a pseudo-element creates an element equal to the child's width inside the child. - The child's
height: auto
property causes it's height to be set by the height of it's own children
Voila! A square!
This trick can also be applied to create boxes of different aspect ratios by changing padding-top
. For example, 16:9 would be padding-top: 52.65%