Episode 6 of 10

Aligning & Justifying Items

Control item alignment within grid cells — use justify-items, align-items, justify-self, and align-self for precise positioning.

Aligning & Justifying Items

Grid cells are often larger than their content. Alignment properties control where items sit within their cells — horizontally (justify) and vertically (align).

The Two Axes

AxisDirectionProperties
Inline (Main)Horizontal →justify-items, justify-self
Block (Cross)Vertical ↓align-items, align-self

Container-Level Alignment

.container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-auto-rows: 200px;

    justify-items: center;  /* Center items horizontally in cells */
    align-items: center;    /* Center items vertically in cells */
}

Values

ValueEffect
startAlign to the start edge
endAlign to the end edge
centerCenter in the cell
stretchFill the entire cell (default)

Item-Level Alignment

.special-item {
    justify-self: end;     /* Override for this item only */
    align-self: start;
}

/* Shorthand */
.center-item {
    place-self: center;    /* align-self + justify-self */
}

Aligning the Entire Grid

.container {
    display: grid;
    grid-template-columns: repeat(3, 200px); /* Fixed-size columns */
    width: 100%;

    justify-content: center;  /* Center the grid horizontally */
    align-content: center;    /* Center the grid vertically */
}

/* Space between tracks */
justify-content: space-between;
justify-content: space-around;
justify-content: space-evenly;

Quick Reference

PropertyApplies ToAxis
justify-itemsAll items (on container)Horizontal
align-itemsAll items (on container)Vertical
justify-selfSingle itemHorizontal
align-selfSingle itemVertical
justify-contentEntire gridHorizontal
align-contentEntire gridVertical
place-itemsShorthandalign-items + justify-items
place-selfShorthandalign-self + justify-self

Key Takeaways

  • justify-* controls horizontal alignment; align-* controls vertical
  • Container properties (-items) set defaults; item properties (-self) override
  • place-items: center is a shorthand for centering items both ways
  • justify-content and align-content position the entire grid within its container