Layout with flexbox
You'll learn to read flexbox and predict where boxes land in a row or a column.
Watch & read
Start with the required ones. The others are there when you need them.
See it step by step
Change one flexbox value at a time and watch the boxes move.
Explanation
You want three buttons side by side with even space, or a photo with your name next to it, centred. By default, boxes stack one under another. You need a way to say "put these in a line, and space them like this".
Think of students lining up for the morning assembly. The teacher does not move each student. The teacher gives the line an instruction: "stand in a row", "move to the middle", "leave a gap". Flexbox works the same way. You style the parent, and the children arrange themselves.
The parent is the flex container. Its direct children are flex items.
.row {display: flex;flex-direction: row;justify-content: center;align-items: center;gap: 8px;}
display: flexturns flexbox on. The children now sit in a line.flex-directionpicks the line:row(side by side) orcolumn(top to bottom). This line is the main axis.justify-contentplaces items along the main axis:flex-start,center,flex-end,space-between.align-itemsplaces items across it, on the other axis:flex-start,center,flex-end,stretch.gapputs space between items, not at the edges.
People often put display: flex on the children instead of the parent, and nothing moves. Put it on the
box that holds the items. The other common one: switching to column and expecting justify-content
to still move things sideways. It follows the main axis, so now it moves things up and down.
On a phone this matters even more. In React Native every box is a flex container, and the default
direction is column, not row.
When you read flexbox, first find the container and its flex-direction. Draw the main axis as an arrow.
Then justify-content is "along the arrow" and align-items is "across the arrow".
Code tour
Click a line number with a ring to read the note for that line.
Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3You want three cards side by side. Where does
display: flexgo? - 2 / 3In a row container, which line puts the items in the middle, left to right?
- 3 / 3With
flex-direction: column, what doesjustify-content: space-betweendo?
Explain it back
How confident are you with Layout with flexbox?
Done
flex-direction, justify-content, align-items and gap on a container and sketch where its items go.