Flexbox

Align flex items

Position items along the main and cross axes with justify-content, align-items, align-self, and gap.

8 minute lesson

~~~

justify-content distributes free space on the main axis. align-items aligns items on the cross axis.

.hero {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 2rem;
}

With flex-direction: row, this distributes items horizontally and aligns them vertically. Switch to column and the axes switch too.

justify-content has visible work only when free space remains after item sizing. If one item grows to consume all available space, changing space-between may appear to do nothing.

align-items defaults to stretch for auto-sized items. align-self overrides cross-axis alignment for one item. Auto margins absorb available space on their axis before distribution, which makes margin-inline-start: auto useful for pushing one navigation action away from its siblings.

gap creates consistent spacing between items without adding space outside the group.

To center one child in both directions:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
}

Give the container a visible outline and a definite minimum height, then enable the Flexbox overlay. Toggle direction and alignment values. Describe the free space and axes first; the resulting position should then be predictable.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →