What they didn’t tell you about Flexbox? (Part 1 — stretch)
I’ve just dipped my toes into the world of Flexbox, and after only a week, I’ve had more “pulling-my-hair-out” moments than I’d care to admit. Seriously, I’ve found myself yelling at my screen, “Why doesn’t justify-content
center my items?", "Why are my cards all different sizes when they're children of the same div?", "Why! Why! WHY!"
Determined to conquer these Flexbox frustrations and optimize my projects, I decided to dive deep into the Flexbox specifications. I set up some sandbox environments to play around with the properties and, surprise surprise, realized I’d missed some crucial details.
So, I put everything I learned into this article — covering Flexbox’s logical properties, element justification, and some practical use cases. Hopefully, this helps you avoid some of my hair-pulling moments and makes your Flexbox journey a bit smoother!
To stretch or not to stretch?
That’s the question.
Here I’m talking about the default stretch given by justify-content and align-items, not justify-content: stretch
.
These are the two properties that I use and combine the most often in Flexbox.
Justify-content will find a way to fill the space around the flexbox-contents
, which includes the difference of the original contents sizes.
In other words, justify-content
might stretch your items by default already.
On the other hand, when CSS executes align-items
, it aligns all items along the cross-axis and can revert them to their original sizes, potentially creating blank space on the cross-axis.
A handy trick to counter this is to add stretch
to align-items
at the container level, or use stretch
with align-self
at the item level. This way, your items stay nicely aligned and fill the space just right!
~Talk is cheap, show me the code.~
Trailer for Part 2: Mind the gap
We use gap
to adjust the space between elements in a flexbox container, but when we mix it with margin/padding, the “empty space” may be hard to debug.
See you in part 2!