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
| Axis | Direction | Properties |
|---|---|---|
| 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
| Value | Effect |
|---|---|
start | Align to the start edge |
end | Align to the end edge |
center | Center in the cell |
stretch | Fill 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
| Property | Applies To | Axis |
|---|---|---|
justify-items | All items (on container) | Horizontal |
align-items | All items (on container) | Vertical |
justify-self | Single item | Horizontal |
align-self | Single item | Vertical |
justify-content | Entire grid | Horizontal |
align-content | Entire grid | Vertical |
place-items | Shorthand | align-items + justify-items |
place-self | Shorthand | align-self + justify-self |
Key Takeaways
justify-*controls horizontal alignment;align-*controls vertical- Container properties (
-items) set defaults; item properties (-self) override place-items: centeris a shorthand for centering items both waysjustify-contentandalign-contentposition the entire grid within its container