Chapter 6

Layout with Flexbox

Use flexbox to arrange items in rows or columns and control their spacing and alignment with a few CSS properties.

Flexbox is a CSS layout tool that makes it easy to arrange items in a row or a column and to space them out neatly. Before flexbox, aligning boxes was tricky; now it takes just a few lines.

Turning on flexbox

You start by setting display to flex on a container. The element you set this on is the flex container, and its direct children become flex items.

.menu {
  display: flex;
}

Direction

The flex-direction property sets the main axis. The value row places items side by side (the default), while column stacks them top to bottom.

Spacing along the main axis

justify-content controls how items are spread along the main axis. Common values are flex-start (packed to the start), center (grouped in the middle), space-between (equal gaps between items), and space-around (equal gaps around each item).

.menu {
  display: flex;
  justify-content: space-between;
}

Alignment across the axis

align-items controls how items line up across the other axis. The value center is very common because it vertically centres a row of items, which used to be hard to do.

Gaps and wrapping

The gap property adds even spacing between flex items without needing margins. If items should drop onto a new line when space runs out, set flex-wrap to wrap.

Remember

  • Set display flex on the container to start.
  • flex-direction chooses row or column.
  • justify-content spaces items along the main axis.
  • align-items lines items up across the other axis.

Stuck on this topic? A verified JomKelas tutor can walk you through it.

Find a verified tutor