CSS Tip #3: CSS Grid Basics
CSS Tip #3: CSS Grid Basics
CSS Grid is a two-dimensional layout system that gives you complete control over both rows and columns. It's perfect for complex layouts!
What is CSS Grid?
CSS Grid Layout is a powerful system that allows you to create complex layouts by defining a grid and placing items within it.
Key Concepts
Grid Container
The parent element with display: grid
Grid Items
The direct children of the grid container
Grid Lines
The horizontal and vertical lines that divide the grid
Grid Tracks
The spaces between grid lines (rows and columns)
Essential Properties
Container Properties
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr 1fr; /* Define column sizes */
grid-template-rows: auto 1fr auto; /* Define row sizes */
gap: 20px; /* Space between items */
grid-template-areas: /* Named grid areas */
"header header header"
"sidebar main main"
"footer footer footer";
}
Item Properties
.grid-item {
grid-column: 1 / 3; /* Start at line 1, end at line 3 */
grid-row: 2 / 4; /* Start at line 2, end at line 4 */
grid-area: main; /* Place in named area */
justify-self: center; /* Align within grid cell */
align-self: center; /* Align within grid cell */
}
Common Patterns
Basic Grid
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
Responsive Grid
.responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
}
Layout with Named Areas
.layout {
display: grid;
grid-template-areas:
"header header header"
"sidebar main main"
"footer footer footer";
grid-template-columns: 200px 1fr 1fr;
grid-template-rows: auto 1fr auto;
min-height: 100vh;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }
Card Grid
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 20px;
padding: 20px;
}
Grid vs Flexbox
| Feature | Grid | Flexbox |
|---|---|---|
| Dimension | 2D (rows + columns) | 1D (row OR column) |
| Use Case | Overall page layout | Component layout |
| Alignment | Built-in | Requires workarounds |
| Browser Support | Modern browsers | Excellent |
Pro Tips
- Use
frunits for flexible sizing repeat()function for repetitive patternsminmax()function for responsive grids- Named areas make layouts more readable
- Grid + Flexbox work great together!
Browser Support
CSS Grid is supported in all modern browsers. Use feature queries for progressive enhancement:
@supports (display: grid) {
.modern-layout {
display: grid;
grid-template-columns: 1fr 2fr;
}
}
Next Up
In two days, we'll cover Responsive Design Patterns - techniques for creating layouts that work beautifully on all devices!
Keep building! 🏗️
Need help with a specific Grid layout? Share your code and I'll provide a solution!
Add a comment: