CSS Grid Mastery: Advanced Layout Techniques
CSS Grid Mastery: Advanced Layout Techniques
Moving beyond the basics of CSS Grid to create complex, responsive layouts with minimal code and maximum flexibility.
Introduction
CSS Grid changed the game for web layouts. But most tutorials stop at the basics. Let's go deeper.
Named Grid Areas
Instead of tracking line numbers, use named areas:
.header { grid-area: header; } .sidebar { grid-area: sidebar; } .main { grid-area: main; } .aside { grid-area: aside; } .footer { grid-area: footer; } ```
Responsive Without Media Queries
Use `auto-fit` and `minmax` for responsive grids:
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1rem;
}
This creates a grid that automatically adjusts based on available space.
Subgrid
Align nested grids with their parent:
.child { display: grid; grid-template-columns: subgrid; grid-column: span 3; } ```
Dense Packing
Fill gaps in your grid automatically:
.masonry {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
grid-auto-flow: dense;
gap: 1rem;
}
Practical Example
Here's a complete dashboard layout:
.widget-small { grid-column: span 3; } .widget-medium { grid-column: span 6; } .widget-large { grid-column: span 12; }
@media (max-width: 768px) { .widget-small, .widget-medium, .widget-large { grid-column: span 12; } } ```
Conclusion
CSS Grid is incredibly powerful when you understand its advanced features. Experiment with these techniques and you'll find yourself reaching for Grid more than Flexbox.