Layout and responsive design
CSS Grid
Goal: Build two-dimensional layouts with columns, rows, fr units and gaps · 11 min
Grid lays items out in two dimensions at once, rows and columns. Use Flexbox for one axis and Grid for a whole layout.
.gallery {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
}
grid-template-columnsdefines the columns;grid-template-rowsthe rows.- The fr unit means "one fraction of the free space":
1fr 2frgives the second column twice the width of the first. repeat(3, 1fr)is shorthand for1fr 1fr 1fr.gap(or row-gap / column-gap) sets the gutters between cells.- Mixing is fine:
200px 1fris a fixed sidebar and a flexible main area. - Placing items:
grid-column: 1 / 3lets an item span from grid line 1 to line 3 (two columns);grid-column: span 2does the same. - Responsive without media queries:
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr))creates as many 200px+ columns as fit.
Calculation: a 330px wide grid with repeat(2, 1fr) and gap: 30px has (330 − 30) / 2 = 150px per column. The gap is subtracted first, then the fractions are divided.
Worked example: A page layout with sidebar
- Two columns: a fixed 220px sidebar and a flexible main area.
- grid-template-columns: 220px 1fr;
- The header can span both columns with grid-column: 1 / -1.
.page {
display: grid;
grid-template-columns: 220px 1fr;
gap: 1rem;
}
header { grid-column: 1 / -1; }