📖
CSS Grid — Layouts Grid
grid-template-columns, fr, gap and grid-area
📐
Grid — Excel for CSS
Flexbox aligns elements in one direction (row or column). Grid is a two-dimensional layout: you define both rows and columns at the same time, then place elements into cells. Like Excel where you can span multiple cells at once.
Grid basics
css
.grid-container {
display: grid;
/* 3 columns: first 200px, second flexible, third 200px */
grid-template-columns: 200px 1fr 200px;
/* 3 equal columns */
grid-template-columns: 1fr 1fr 1fr;
grid-template-columns: repeat(3, 1fr); /* shorthand */
/* Auto columns minimum 250px */
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
/* Rows */
grid-template-rows: 80px 1fr 60px;
/* Gaps */
gap: 24px; /* rows and columns */
row-gap: 16px; /* rows only */
column-gap: 24px; /* columns only */
}fr (fractional unit) — a fraction of free space. 1fr 2fr — first takes 1/3, second 2/3.
Placing elements
css
/* Span multiple cells */
.item {
grid-column: 1 / 3; /* from line 1 to line 3 (2 columns) */
grid-column: span 2; /* span 2 columns (simpler) */
grid-row: span 2; /* span 2 rows */
}
/* Named areas — most readable approach */
.layout {
display: grid;
grid-template-columns: 280px 1fr;
grid-template-rows: 80px 1fr 60px;
grid-template-areas:
'header header'
'sidebar main'
'footer footer';
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }css
💬
repeat(auto-fill, minmax(280px, 1fr)) — one line of CSS instead of three media queries. The magic of Grid.
Flexbox or Grid? Simple rule: if you're arranging elements IN ONE DIRECTION (row or column) — Flexbox. If you need a TWO-DIMENSIONAL grid (rows AND columns at the same time) — Grid.