DevNotes
@devnotes ·
CSS Part 5: Line things up with flexbox
Putting things side by side used to take tricks. With flexbox it takes a few lines. Flexbox lays items out in one direction, as a row or as a column.
Turn it on
Flexbox goes on the parent, and it arranges the parent's direct children:
The links now sit in a row with 16px between them. gap is the clean way to space flex items, with no margins needed.
Two axes
Flexbox thinks in two directions:
- The main axis is the way the items flow. In a row, it runs left to right.
- The cross axis runs across it. In a row, that's top to bottom.
justify-content arranges items along the main axis, and align-items along the cross axis. Almost everyone mixes those two up at first. Think in axes and it stops happening.
Values you'll use for justify-content:
flex-start: packed at the start, which is what you get by defaultcenter: packed in the middlespace-between: first item at the start, last at the end, equal gaps in betweenspace-evenly: equal space between the items and at both ends
For align-items: stretch (the default, items fill the height), flex-start, center and flex-end.
Columns
Now the main axis runs top to bottom, so justify-content works vertically and align-items horizontally. The axes turn with the direction.
Centring anything
The classic question, answered in three lines:
Whatever sits inside .box ends up dead centre.
Growing and wrapping
flex: 1 on an item tells it to take up the leftover space. In a search bar, the input stretches and the button stays its natural size:
By default, items squeeze onto one line. flex-wrap: wrap lets them move to the next line when they run out of room, which is handy for a set of tags or buttons on a phone.
A real header
With a logo and a <nav> inside, this puts the logo on the left and the menu on the right, both lined up vertically. You'll write some version of this on almost every site you build.
Try it
Play flexboxfroggy.com to the end. It's 24 short levels, about twenty minutes, and the two axes will make sense by the end. Then use flexbox for the header and menu of your portfolio page.
Next: CSS Part 6: Page layouts with grid
Join WIK to like and reply to DevNotes and see more like this.