Learn how to create complex page layouts (headers, sidebars, footers) in seconds using CSS Grid.
Flexbox (1D)
Items flow in a single line (row or column).
1
2
3
CSS Grid (2D)
Items align in rows AND columns simultaneously.
1
2
3 (Spans 2 cols)
Grid vs. Flexbox
Flexbox is designed for one dimension (a row or a column). CSS Grid is designed for two dimensions (rows and columns at the same time). It is perfect for overall page layout.
Defining the Grid
To start, define a container and tell it how many columns you want. The fr unit means “fraction of available space”.
.container {
display: grid;
/* Create 3 columns: 1st is 200px, 2nd fills space, 3rd is 200px */
grid-template-columns: 200px 1fr 200px;
gap: 20px; /* Space between grid cells */
}
Placing Items
You can tell a specific item to span across multiple columns or rows.
.header {
/* Span from column line 1 to line 4 (the end) */
grid-column: 1 / 4;
}