CSS Grid: The Complete Layout Guide
CSS • Web Development • 7 min read
CSS Grid handles two-dimensional layouts. Learn columns, rows, placement, and responsive grids.
CSS Grid: The Complete Layout Guide
CSS Grid is a two-dimensional layout system. It handles rows and columns simultaneously, making complex layouts simple. Grid and Flexbox together cover all your layout needs.
What is CSS Grid?
CSS Grid lets you create layouts with rows and columns. You define the grid structure, then place items exactly where you want them.
Basic Grid
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
/* Result: 3 equal columns with 20px gap */
Defining Columns
/* Fixed width columns */
grid-template-columns: 200px 200px 200px;
/* Flexible columns */
grid-template-columns: 1fr 2fr 1fr; /* 1:2:1 ratio */
/* Repeat syntax */
grid-template-columns: repeat(4, 1fr); /* 4 equal columns */
/* Auto-fit */
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
Placing Items
/* Span multiple columns */
.item {
grid-column: span 2;
}
/* Span multiple rows */
.item {
grid-row: span 2;
}
/* Specific placement */
.item {
grid-column: 1 / 3; /* Start at line 1, end at line 3 */
grid-row: 1 / 2;
}
Responsive Grid Without Media Queries
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
}
/* Items automatically wrap based on available space */
Grid vs Flexbox
| Feature | Flexbox | Grid |
|---|---|---|
| Dimensions | One-dimensional | Two-dimensional |
| Best for | Components, small layouts | Page layouts, complex grids |
| Alignment | Single axis | Both axes |
Real Example: Dashboard Layout
.dashboard {
display: grid;
grid-template-columns: 250px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"sidebar header"
"sidebar main"
"sidebar footer";
min-height: 100vh;
}
.sidebar { grid-area: sidebar; }
.header { grid-area: header; }
.main { grid-area: main; }
.footer { grid-area: footer; }
Note: Use Grid for page layouts and Flexbox for components. They complement each other — learn both.