October 21, 2018
Share this:

How to keep your Flexbox square

If you're transitioning from absolute layouts into flex-box, you end up with this annoying situation where you want to keep something square (or at least at a 1:1 ratio).

Flex-box is supremely powerful at spacing things out beautifully, and sizing them according to their parent elements, but it can be a royal pain when you want to size things according to itself.

Today, I'm going to show you a little trick that's been floating around the internet for a while about how to keep your flex items square:

.parent {
	display: flex;

.child {
	flex-basis: auto;
	height: auto;

.child:before {
	content: '';
	padding-top: 100%;

That's it. It's super simple.

The way it works is by making use of the fact that padding percentage is calculated from the parent's width.

Voila! A square!

Things to note: if you want to place other elements inside the .child container, you need to make sure the flow of the elements don't interact

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: