Flexbox is one of those CSS features that changes everything once you get it. Before flexbox, aligning items horizontally or vertically was a nightmare. We used floats, tables, inline-block hacks โ all kinds of ugly workarounds. Flexbox fixes all of that.
Think of flexbox as a way to tell the browser: "distribute this space among these children in a flexible way." You set up a flex container, and the items inside it become flex items that automatically arrange themselves.
The Main Axis and Cross Axis
Flexbox works along two lines: the main axis and the cross axis. By default, the main axis runs left to right (horizontal), and the cross axis runs top to bottom (vertical).
Everything you do with flexbox is about controlling how items behave along these two axes. Do you want them side by side? That is the main axis. Do you want them centered vertically? That is the cross axis.
.container {
display: flex;
}
That one line turns your container into a flex container. Its children will now sit side by side instead of stacking vertically. Simple, right?
Try it Yourself โFlipping the Axes
You can swap the axes using flex-direction. Set it to column, and the
main axis becomes vertical. Your items stack top to bottom instead of left to right.
.container {
display: flex;
flex-direction: column;
}
This is useful when you want the flexbox layout power but need items to stack vertically โ like a column of cards or a vertical navigation menu.