Understanding CSS Grid Layout
CSS Grid has revolutionized how we create layouts on the web. Let’s dive deep into this powerful layout system.
Grid Basics
Create a grid container and define your columns and rows:
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: auto;
gap: 1rem;
}
Key Terminology
- Grid Container - The element with
display: grid - Grid Items - Direct children of the container
- Grid Lines - The dividing lines that make up the structure
- Grid Tracks - The space between two adjacent grid lines
- Grid Cell - A single unit of the grid
- Grid Area - One or more cells forming a rectangular area
Defining Columns and Rows
Fixed and Flexible Sizes
.grid {
/* Fixed width columns */
grid-template-columns: 200px 200px 200px;
/* Flexible columns */
grid-template-columns: 1fr 2fr 1fr;
/* Mixed */
grid-template-columns: 200px 1fr 200px;
}
The repeat() Function
.grid {
/* Creates 12 equal columns */
grid-template-columns: repeat(12, 1fr);
/* Auto-fill for responsive grids */
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
}
Placing Items
Line-Based Placement
.item {
grid-column: 1 / 3; /* Spans from line 1 to line 3 */
grid-row: 1 / 2;
}
/* Shorthand */
.item {
grid-area: 1 / 1 / 2 / 3; /* row-start / col-start / row-end / col-end */
}
Named Grid Areas
.container {
grid-template-areas:
"header header header"
"sidebar main main"
"footer footer footer";
}
.header {
grid-area: header;
}
.sidebar {
grid-area: sidebar;
}
.main {
grid-area: main;
}
.footer {
grid-area: footer;
}
Responsive Grids
Create layouts that adapt without media queries:
.responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 1.5rem;
}
Grid vs Flexbox
| Use Case | Grid | Flexbox |
|---|---|---|
| Two-dimensional layouts | ✅ | ❌ |
| One-dimensional layouts | ✅ | ✅ |
| Content-driven sizing | ❌ | ✅ |
| Layout-driven sizing | ✅ | ❌ |
Practical Example: Card Layout
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 2rem;
padding: 2rem;
}
.card {
display: grid;
grid-template-rows: 200px 1fr auto;
}
.card-image {
/* Spans the image area */
}
.card-content {
/* Flexible content area */
}
.card-footer {
/* Fixed footer */
}
Conclusion
CSS Grid is incredibly powerful for creating complex layouts with clean, maintainable code. Combined with Flexbox for component-level layouts, you have all the tools needed for modern web design.
Practice with real projects, and soon grid layouts will become second nature!