Grid Container
Grid Container
A grid layout starts by turning an element into a grid container. Set display: grid (or inline-grid) on the parent, and its direct children become grid items.
.grid {
display: grid;
}
inline-grid makes the container behave like an inline element (it takes only the needed width):
.grid-inline {
display: inline-grid;
}
Most grids define columns first, then optionally rows:
.grid {
display: grid;
grid-template-columns: 220px 1fr;
grid-template-rows: auto;
}
Grid Tracks
Columns and rows in Grid are called tracks. You define them using:
grid-template-columns– column tracksgrid-template-rows– row tracks
Fixed + flexible tracks:
.grid {
display: grid;
grid-template-columns: 260px 1fr;
}
Using fr units:
.grid {
display: grid;
grid-template-columns: 1fr 2fr 1fr;
}
Using repeat():
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
Responsive tracks with minmax():
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
}
Tip: auto-fit collapses empty columns; auto-fill keeps the tracks even if there are fewer items.
Grid Gaps
gap controls spacing between grid tracks (between rows and columns). This is cleaner than margins for grid spacing.
One value for both directions:
.grid {
display: grid;
gap: 14px;
}
Separate row and column gaps:
.grid {
display: grid;
row-gap: 18px;
column-gap: 12px;
}
Or shorthand: gap: row-gap column-gap
.grid {
display: grid;
gap: 18px 12px;
}
Grid Align
Grid has two sets of alignment controls:
- Align the entire grid inside the container (when there is extra space)
- Align items inside their grid cells
1) Align the grid as a whole:
justify-content– horizontal alignment of the grid tracksalign-content– vertical alignment of the grid tracks
.grid {
display: grid;
width: 800px;
height: 320px;
grid-template-columns: repeat(3, 160px);
grid-template-rows: repeat(2, 120px);
gap: 14px;
justify-content: center;
align-content: center;
}
2) Align items inside their cells:
justify-items– horizontal alignment of items within their cellsalign-items– vertical alignment of items within their cells
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 14px;
justify-items: center;
align-items: center;
}
Per-item override: use justify-self / align-self.
.item-right {
justify-self: end;
}
.item-bottom {
align-self: end;
}
Summary
- Create a grid container with
display: grid/inline-grid. - Define tracks with
grid-template-columnsandgrid-template-rows. - Use
gapfor clean spacing between tracks. - Use
justify-content/align-contentto align the grid, andjustify-items/align-itemsto align items.