Last Updated: November 18, 2020
Share this:
Basics CSS

How to Keep Your Flexbox Square

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.

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%

Can't get past JavaScript Tutorials?

Download my FREE ebook on how to succeed as a self-taught JavaScript Developer, and how to find projects that you'll actually finish. Learn More...

Share this: