Complete reference for CSS Grid layout with examples and common patterns
Defines the element as a grid container
display: grid;
Defines the columns of the grid
grid-template-columns: repeat(3, 1fr);
Defines the rows of the grid
grid-template-rows: 100px 200px;
Defines grid areas by referencing grid-area names
grid-template-areas:
"header header header"
"sidebar main main"
"footer footer footer";
Shorthand for grid-row-gap and grid-column-gap
grid-gap: 20px;
Aligns grid items along the inline (row) axis
justify-items: center;
Aligns grid items along the block (column) axis
align-items: center;
Specifies which columns the item spans
grid-column: 1 / 3;
Specifies which rows the item spans
grid-row: 1 / 2;
Gives an item a name or specifies its location
grid-area: header;
Aligns a grid item along the inline axis
justify-self: end;
Aligns a grid item along the block axis
align-self: center;
Classic 12-column grid system
.grid {
display: grid;
grid-template-columns: repeat(12, 1fr);
gap: 20px;
}
.col-1 { grid-column: span 1; }
.col-2 { grid-column: span 2; }
.col-3 { grid-column: span 3; }
.col-4 { grid-column: span 4; }
.col-6 { grid-column: span 6; }
.col-12 { grid-column: span 12; }
Header, sidebar, main content, and footer layout
.layout {
display: grid;
grid-template-areas:
"header header header"
"sidebar main main"
"footer footer footer";
grid-template-rows: 80px 1fr 60px;
grid-template-columns: 250px 1fr 1fr;
min-height: 100vh;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }
Auto-fit grid that adapts to screen size
.responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
padding: 20px;
}
Grid with varying item heights
.masonry {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
grid-auto-rows: 0;
grid-template-rows: masonry;
gap: 16px;
}
Use fr
units for flexible columns that distribute available space
Combine minmax()
with auto-fit
for responsive grids
Use grid-template-areas
for semantic layouts
Prefer gap
over margins for spacing between grid items