Aligning Items in a Grid Container
- CSS Basics
- Selectors & Specificity
- Box Model & Units
- Typography & Text Styling
- Colors & Color Spaces
- Positioning & Stacking Context
- Flexbox
- Grid
- Grid Advanced
- Responsive Design
- Container Queries
- Pseudo-classes & Pseudo-elements
- Modern Selectors
- CSS Custom Properties
- CSS Functions
- Transitions & Animations
- Transforms
- Forms & Input Styling
- CSS Architecture & Methodologies
- Accessibility in CSS
- Performance & Optimization
- View Transitions & Modern APIs
- Cascade Layers & Scope
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
| Property | Affects | Axis |
|---|---|---|
| justify-content | The whole track set | Horizontal |
| align-content | The whole track set | Vertical |
| justify-items / justify-self | Item(s) within their cell | Horizontal |
| align-items / align-self | Item(s) within their cell | Vertical |