Grid Fundamentals
CSS Grid is a two-dimensional layout system, handling rows and columns simultaneously — where Flexbox excels at a single row or column, Grid excels at full page and component layouts.
.container {
display: grid;
grid-template-columns: 200px 1fr 1fr;
grid-template-rows: auto 1fr auto;
gap: 16px;
}
grid-template-columns defines the column tracks. 1fr represents "one fractional unit" of the remaining available space — 200px 1fr 1fr creates a fixed 200px sidebar followed by two equally-sized flexible columns sharing whatever space is left.
A common responsive pattern without media queries:
.gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 16px;
}
repeat(auto-fit, minmax(200px, 1fr)) tells the browser: fit as many 200px-minimum, flexible columns as will comfortably fit in the container, then let them grow evenly to fill any remaining space. As the browser window resizes, columns automatically wrap and re-flow without a single @media rule.
Placing items on specific grid lines:
.item {
grid-column: 1 / 3; /* spans from column line 1 to column line 3 */
grid-row: 2 / 4;
}
Grid lines are numbered starting at 1, and grid-column: 1 / 3 means the item spans two column tracks (from line 1 to line 3), which is a very different mental model than Flexbox's linear one-dimensional flow.