CSS Grid
2D layout with rows, columns, and areas
Skills taught: css.grid, css.grid-template, css.grid-areas
Defining columns and rows
.grid {
display: grid;
/* Three equal columns */
grid-template-columns: 1fr 1fr 1fr;
grid-template-columns: repeat(3, 1fr); /* same thing */
/* Mixed columns: sidebar + main */
grid-template-columns: 240px 1fr;
/* Responsive: as many 200px+ columns as fit */
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
/* Rows */
grid-template-rows: auto 1fr auto; /* header | content | footer */
gap: 24px; /* space between all tracks */
gap: 16px 24px; /* row-gap column-gap */
}
Named grid areas
.layout {
display: grid;
grid-template-areas:
'header header '
'sidebar main '
'footer footer ';
grid-template-columns: 240px 1fr;
grid-template-rows: auto 1fr auto;
min-height: 100vh;
gap: 0;
}
header { grid-area: header; }
.sidebar { grid-area: sidebar; }
main { grid-area: main; }
footer { grid-area: footer; }
Spanning items across tracks
/* Span 2 columns */
.wide { grid-column: span 2; }
/* Span 2 rows */
.tall { grid-row: span 2; }
/* Explicit placement: start-line / end-line */
.feature {
grid-column: 1 / 3; /* from column line 1 to line 3 */
grid-row: 1 / 2;
}
Tip: repeat(auto-fill, minmax(200px, 1fr)) is the most powerful one-liner in CSS — it creates as many columns as fit, each at least 200px wide, and expands them to fill the row. Zero media queries needed.
Frequently Asked Questions
When should I use Grid vs Flexbox?
Use Grid for 2D layouts where you control both rows and columns — page layouts, card grids, dashboard panels. Use Flexbox for 1D layouts — a single row of items or a column of stacked items. They are often used together: Grid for the page structure, Flexbox for components inside grid areas.
What is auto-fill vs auto-fit?
auto-fill creates as many tracks as fit and adds empty tracks for leftover space. auto-fit collapses empty tracks to 0 width and stretches remaining items. For most card grids, auto-fill is correct.
What is minmax()?
minmax(min, max) defines a track's minimum and maximum size. minmax(200px, 1fr) means 'at least 200px, but can grow up to 1fr of free space'.