Grid vs Flexbox
Flexbox is one-dimensional — it controls items along a single axis (row or column). CSS Grid is two-dimensional — it controls rows and columns simultaneously. Use Flexbox for components, Grid for page-level layouts.
Defining a Grid
Turn any element into a grid container with display: grid, then define your columns and rows:
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: auto;
gap: 1.5rem;
}
The 1fr unit means "one fraction of available space" — a proportional unit unique to Grid.
Placing Items
Grid items can be explicitly placed to span multiple columns or rows:
.featured {
grid-column: 1 / 3; /* spans columns 1 and 2 */
grid-row: 1 / 2;
}
/* shorthand */
.hero {
grid-area: 1 / 1 / 3 / 4; /* row-start / col-start / row-end / col-end */
}
Named Grid Areas
For complex layouts, naming areas makes the code read like a diagram:
.layout {
display: grid;
grid-template-areas:
"header header header"
"sidebar main main"
"footer footer footer";
grid-template-columns: 240px 1fr 1fr;
}
header { grid-area: header; }
aside { grid-area: sidebar; }
main { grid-area: main; }
footer { grid-area: footer; }
Responsive Grids Without Media Queries
The most powerful CSS Grid trick — a fully responsive grid with zero media queries:
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 1rem;
}
auto-fill creates as many columns as fit. minmax(280px, 1fr) ensures each column is at least 280px but expands to fill available space. The grid reflows automatically at every breakpoint.
Discussion
Loading comments…
Leave a comment
Related Articles


