DevNotes

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:

HTML
<nav class="menu">  <a href="/">Home</a>  <a href="/courses">Courses</a>  <a href="/contact">Contact</a></nav>
CSS
.menu {  display: flex;  gap: 16px;}

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.

CSS
.menu {  display: flex;  justify-content: space-between; /* along the row */  align-items: center;            /* up and down */}

Values you'll use for justify-content:

  • flex-start: packed at the start, which is what you get by default
  • center: packed in the middle
  • space-between: first item at the start, last at the end, equal gaps in between
  • space-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

CSS
.sidebar {  display: flex;  flex-direction: column;}

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:

CSS
.box {  display: flex;  justify-content: center;  align-items: center;  min-height: 300px;}

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:

CSS
.search { display: flex; gap: 8px; }.search input { flex: 1; }

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

CSS
.site-header {  display: flex;  justify-content: space-between;  align-items: center;  padding: 1rem 2rem;}

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

csswebdevbeginners

Join WIK to like and reply to DevNotes and see more like this.