Field Guide / intermediate

Alignment in CSS: separate item alignment from track distribution

CSS alignment gets easier when you separate aligning items from distributing leftover space.

Alignment bugs are often vocabulary bugs. align-items, justify-items, align-content, and justify-content sound similar, but they answer different questions.

Start with two distinctions:

  • Are you aligning items inside their own area?
  • Are you distributing leftover space between tracks or lines?

Once that is clear, most alignment rules become predictable.

Items vs content

align-items and justify-items align the item inside its grid area or flex line. align-content and justify-content distribute the tracks or flex lines inside the container when extra space exists.

.cluster {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

This centers items on the cross axis and distributes remaining inline space between them. Those are two separate jobs.

Grid makes both axes explicit

Grid gives you two-dimensional alignment controls.

.badge-grid {
  display: grid;
  place-items: center;
}

place-items is a useful shorthand when you genuinely want both axes to share the same item alignment. It is less useful when one axis is about tracks and the other is about item placement.

Flexbox has a main axis

In Flexbox, justify-content follows the main axis. If flex-direction changes, the axis changes too. That is why a rule can appear to “stop working” when a component switches from row to column.

.stack {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

This centers along the block axis because the main axis is vertical. If the goal is inline centering, align-items is the property to inspect.

The production approach

Write the alignment rule that matches the job, then leave a clear sizing context. Alignment cannot distribute space that does not exist. If a container has no extra block size, align-content will not create a visible change. If a grid item stretches by default, justify-items may be hidden by the item filling its cell.

When debugging alignment, temporarily add borders to the container, the track area, and the item. Seeing which box owns the empty space usually reveals the property you actually need.

References