Loading content…
Loading content…
Master two-dimensional layouts using CSS Grid, responsive auto-fitting templates, and layout alignment rules
display: grid on a container. You can establish columns and rows using the fractional (fr) unit, which represents a share of the available free space..container {
display: grid;
/* Create three columns: 1st takes 200px, 2nd & 3rd share the rest equally */
grid-template-columns: 200px 1fr 1fr;
/* Create two rows of 100px and 200px */
grid-template-rows: 100px 200px;
/* Space between grid items */
gap: 1.5rem;
}
Grid Lines:
1 2 3 4
├──────────┼──────────┼──────────┤ Row Line 1
│ Item 1 │ Item 2 │ Item 3 │
├──────────┼──────────┼──────────┤ Row Line 2
│ Item 4 │ Item 5 │ Item 6 │
└──────────┴──────────┴──────────┘ Row Line 3
grid-column and grid-row properties:.hero-item {
/* Starts at column line 1, spans to column line 3 */
grid-column: 1 / 3;
/* Starts at row line 1, spans to row line 2 */
grid-row: 1 / 2;
}
/* Shorthand using span keyword */
.sidebar {
grid-column: span 1; /* Spans 1 column track */
grid-row: span 2; /* Spans 2 row tracks */
}
@media queries. This is achieved using repeat, minmax, and auto-placement keywords:auto-fill: Fills the row with as many columns as will fit, even if they are empty.auto-fit: Fills the row with columns, and stretches them to take up any empty space..responsive-card-grid {
display: grid;
/* Columns will be at least 250px, but will grow to share space equally */
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 2rem;
}
grid-template-areas provides a readable way to arrange elements:.page-layout {
display: grid;
grid-template-columns: 240px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
height: 100vh;
}
header { grid-area: header; }
aside { grid-area: sidebar; }
main { grid-area: main; }
footer { grid-area: footer; }
| Property | Flexbox | CSS Grid |
|---|---|---|
| Dimension | 1D Layout (Row or Column) | 2D Layout (Row AND Column) |
| Approach | Content-first (items size themselves) | Layout-first (container defines tracks) |
| Alignment | Along a single main axis | Across intersection cell tracks |
| Use Case | Navbars, buttons lists, simple forms | Dashboard panels, card grids, full page templates |
Senior Developer Wisdom
Common Pitfall
repeat(auto-fit, ...)), be careful with padding and borders. If they cause grid items to exceed the container width, elements will wrap unexpectedly. Always use box-sizing: border-box globally.CSS Grid Checklist
fr) distribute empty container space proportionally.Marking it complete updates your roadmap progress percentage.