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.

  • We allow for display:flex to set widths 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!

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

  • Put float: left on the pseudo-element
  • Or, put position: relative on .child, and make other direct children position: absolute
Show Comments