π What is CSS Grid?
CSS Grid is a powerful 2-dimensional layout system that allows developers to create complex, responsive web layouts with ease. Unlike Flexbox (which is 1-dimensional), Grid controls both rows and columns at the same time β making it perfect for full-page layouts, dashboards, galleries, and component structures.
π‘ Why Use CSS Grid?
- Control over both rows and columns simultaneously
- Cleaner and more readable layout code
- Built-in responsive features (auto-fit, minmax, fr units)
- Perfect for both small components and full-page layouts
- Reduces the need for frameworks like Bootstrap for layout
π§± Basic Terminology in CSS Grid
1οΈβ£ Grid Container
The parent element that holds the grid layout. You define it using:
Define a Grid Container
.container {
display: grid;
}2οΈβ£ Grid Items
All direct children of the grid container automatically become grid items.
3οΈβ£ Tracks (Rows & Columns)
Grid uses tracks to define layout structure:
- grid-template-columns β defines columns
- grid-template-rows β defines rows
Creating Rows & Columns
.container {
display: grid;
grid-template-columns: 200px 1fr 200px;
grid-template-rows: 100px 200px;
}π§© A Simple Example
Letβs create a basic 3-column grid layout:
Simple Grid Example
.grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 20px;
}
.item {
background: lightblue;
padding: 20px;
border-radius: 8px;
}
π Important Grid Units
| Unit | Description |
|---|---|
| fr | Fractional unit β divides available space |
| px | Fixed size in pixels |
| % | Percentage based sizing |
| auto | Adjusts to content size |
| minmax() | Defines min and max constraints for responsive grid |
π² Responsive Grid Example
Using repeat() and minmax() makes grids responsive without media queries:
Responsive Auto-Fit Grid
.gallery {
display: grid;
gap: 20px;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}Note
π― When to Use CSS Grid?
- Page layouts with header/sidebar/content/footer
- Image galleries
- Dashboards
- Card-based layouts
- Forms with complex alignment
π₯ Summary
CSS Grid is a next-generation layout system that is flexible, powerful, and easier to maintain. If you're building responsive layouts, Grid is one of the best tools in modern CSS.
Ready to go deeper? Learn more onMDN Docs π