🎓 A1Learner
🔍
0 of 54 lessons completed

CSS Flexbox Alignment

Flexbox alignment controls where flex items sit inside their container. justify-content spreads items along the main axis, and align-items lines them up on the cross axis.

Spread items to the edges

space-between pushes the first item to the start and the last item to the end. The padding is set to zero so the edges line up exactly.

ul {
  display: flex;
  justify-content: space-between;
  width: 400px;
  padding: 0;
}

Centre items on the cross axis

The list is given a height of 100 pixels. align-items center places each item halfway down that height.

ul {
  display: flex;
  align-items: center;
  height: 100px;
}

Fixed space between items

gap sets the same space between every pair of items. The space does not grow or shrink with the container.

ul {
  display: flex;
  gap: 16px;
}

Example

ul {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  width: 400px;
  height: 100px;
  padding: 0;
}

Key points

  • justify-content: sets how items spread along the main axis
  • align-items: sets how items line up on the cross axis
  • gap: sets a fixed space between items
  • justify-content also accepts flex-start, flex-end, center, space-around and space-evenly
  • align-items stretch is the default value
  • gap also sets the space between rows when items wrap

In this example, the list becomes a flex row with a fixed width and height. justify-content spreads the items to the two ends of the row. align-items centres each item within the height of the list. gap keeps at least 16 pixels between neighbouring items.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

Which property spreads flex items along the main axis?