HTML & CSS Foundations · 18 min · 130 XP

Flexbox basics

Lay things out in a row or a column, and align them on both axes.

display: flex on a container lays its children out along a line: a row by default, or a column with flex-direction: column. That line is the main axis, and across it runs the cross axis. Nearly all of flexbox is two questions: how should items be spread along the main axis, and how should they sit across it?

css
.site-header {
  display: flex;
  justify-content: space-between;  /* main axis: start, center, space-between… */
  align-items: center;             /* cross axis: stretch (default), center, start… */
  gap: 1rem;                       /* space between items */
}

Items can grow and shrink with flex: 1 (take a share of the spare space) or flex: none (stay their natural size). flex-wrap: wrap lets items move onto a new line instead of squashing. And a handy trick: margin-left: auto on one item pushes it, and everything after it, to the far end.

Loading your workspace…