Aligning Items in a Grid Container

Alignment Happens at Two Levels

Grid alignment properties work at two levels: aligning the whole set of tracks within the container, and aligning an individual item within its own cell. Mixing these up is a common source of confusion.

Aligning the Tracks Themselves

.grid {
  display: grid;
  grid-template-columns: repeat(3, 100px);
  justify-content: center; /* centers the whole track set horizontally */
  align-content: center;   /* centers the whole track set vertically */
}

These only have a visible effect when the grid's tracks take up less space than the container itself - for example, three 100px columns inside a much wider container.

Aligning Items Within Their Cells

.grid {
  display: grid;
  justify-items: center; /* centers each item horizontally in its own cell */
  align-items: center;   /* centers each item vertically in its own cell */
}

Overriding Alignment for One Item

.item-special {
  justify-self: end;
  align-self: start;
}

justify-self and align-self let one specific item break away from the container's justify-items/align-items default, the same way align-self works in Flexbox.

Quick Reference

PropertyAffectsAxis
justify-contentThe whole track setHorizontal
align-contentThe whole track setVertical
justify-items / justify-selfItem(s) within their cellHorizontal
align-items / align-selfItem(s) within their cellVertical
Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.