CSS Grid
Grid is one of the most powerful tools in CSS. Once you understand it, designing page layouts becomes dramatically easier and more predictable.
Enabling Grid
Add display: grid to a container. Its direct children become grid items.
.container {
display: grid;
}
Defining Columns and Rows
Use grid-template-columns to define how many columns the grid has and how wide each one is:
/* Three equal columns */
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
/* Shorthand with repeat() */
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
The fr unit stands for fraction — it divides the available space proportionally. 1fr 2fr gives you one column that is twice as wide as the other.
/* Two columns: sidebar + main content */
.layout {
display: grid;
grid-template-columns: 240px 1fr;
gap: 2rem;
}
gap
Use gap to add space between grid tracks (rows and columns):
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1.5rem; /* same gap in all directions */
}
/* Or set row and column gap separately */
.grid {
row-gap: 2rem;
column-gap: 1rem;
}
auto-fill and auto-fit
These keywords let the grid automatically create as many columns as will fit — perfect for responsive card grids:
.cards {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 1.5rem;
}
This creates columns that are at least 250px wide. The grid adds as many columns as the container allows, and they each grow to fill the remaining space.
auto-fill vs auto-fit: use auto-fill to keep empty column tracks, and auto-fit to collapse them. For most card grids, auto-fill is the right choice.
Spanning Columns and Rows
Grid items can span multiple columns or rows:
.featured {
grid-column: span 2; /* takes up 2 columns */
}
.banner {
grid-column: 1 / -1; /* spans the full width (1 to last line) */
}
Placing Items Explicitly
.item {
grid-column: 2 / 4; /* starts at column line 2, ends at line 4 */
grid-row: 1 / 3; /* starts at row line 1, ends at line 3 */
}
A Complete Page Layout
.page {
display: grid;
grid-template-columns: 240px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"sidebar header"
"sidebar main"
"sidebar footer";
min-height: 100vh;
gap: 0;
}
.sidebar { grid-area: sidebar; }
.header { grid-area: header; }
.main { grid-area: main; }
.footer { grid-area: footer; }
Have anything to say about this lesson?
Your feedback helps improve these tutorials. If something was confusing or missing, let us know.