2.5 Layout with Flexbox
Now that you know "every element is a box," the next question is: how do you arrange these boxes? Lay a nav menu out horizontally, center content vertically, distribute a few cards evenly… all of this used to be painful. Now we have Flexbox, built exactly for this kind of arrangement.
The lab below has a few switches. Tweak them and watch three squares rearrange in real time.
Turn on Flexbox with one line
Just add display: flex to the container and its direct children automatically line up in a row:
.container {
display: flex;
}<div class="container">
<div>1</div>
<div>2</div>
<div>3</div>
</div>That simple — the three <div>s go from "one per line" to "side by side in a row."
Two axes: main and cross
The heart of Flexbox is understanding the two axes:
- Main axis: the direction children line up, horizontal by default (left to right).
- Cross axis: perpendicular to the main axis, vertical by default.
Two key properties control these axes:
.container {
display: flex;
justify-content: center; /* main axis: how to distribute */
align-items: center; /* cross axis: how to align */
}Common justify-content values:
flex-start(default, at the start)
center(centered)
flex-end(at the end)
space-between(push to both ends, spread the rest)
space-around(equal space around each element)
A classic use: perfect centering
Centering an element horizontally and vertically used to be a notorious CSS headache. With Flexbox, three lines do it:
.container {
display: flex;
justify-content: center; /* horizontal center */
align-items: center; /* vertical center */
}Change the direction
The main axis is horizontal by default; add flex-direction: column to stack children vertically:
.container {
display: flex;
flex-direction: column; /* stack vertically */
}