Learn about CSS Grid, a powerful layout system for creating two-dimensional grid-based layouts in web design.
What is CSS Grid?
CSS Grid is a powerful layout system that allows you to create two-dimensional grid-based layouts for web pages. It provides precise control over both rows and columns, making it ideal for complex page layouts.
Understanding CSS Grid
CSS Grid is a layout method designed for the two-dimensional layout of items on a webpage. Unlike Flexbox, which is primarily for one-dimensional layouts, Grid excels at creating complex, responsive layouts.
Key Concepts
Basic Grid Setup
Creating a Grid Container
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: auto auto;
gap: 20px;
}
Grid Template Properties
Grid Units and Values
Fractional Units (fr)
grid-template-columns: 1fr 2fr 1fr; /* 1:2:1 ratio */
Fixed Units
grid-template-columns: 200px 300px 200px;
Mixed Units
grid-template-columns: 200px 1fr 2fr;
Auto Units
grid-template-columns: auto 1fr auto;
Grid Item Positioning
Grid Line Positioning
.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 Positioning
.item {
grid-area: header; /* Use named grid area */
}
Spanning Items
.item {
grid-column: span 2; /* Span 2 columns */
grid-row: span 3; /* Span 3 rows */
}
Responsive Grid Layouts
Auto-Fit and Auto-Fill
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
Media Queries
.container {
grid-template-columns: 1fr;
}
@media (min-width: 768px) {
.container {
grid-template-columns: 1fr 1fr;
}
}
Common Grid Patterns
Holy Grail Layout
.container {
display: grid;
grid-template-areas:
"header header header"
"nav main aside"
"footer footer footer";
grid-template-columns: 200px 1fr 200px;
grid-template-rows: auto 1fr auto;
}
Card Grid
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 20px;
}
Photo Gallery
.gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
grid-auto-rows: 200px;
gap: 10px;
}
Grid vs Flexbox
When to Use Grid
When to Use Flexbox
Browser Support
Modern Browsers
Fallbacks
.container {
display: flex; /* Fallback */
display: grid; /* Modern browsers */
}
Tools and Resources
CSS Grid Generators
Use our CSS Grid tools to visualize and generate grid layouts for your projects.
Learning Resources
Best Practices
Naming Conventions
Performance
Accessibility
CSS Grid has revolutionized web layout, providing developers with powerful tools to create sophisticated, responsive designs that were previously difficult or impossible to achieve.