What Is CSS Grid?
CSS Grid is a 2-dimensional layout system (rows + columns). Flexbox = one direction (row *or* column) Grid = both directions at the same time.
Basic Grid
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr; /* 3 equal columns */
gap: 10px;
}
Grid Items
Grid items automatically place themselves into the next available cell.
<div class="container">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
</div>
<style>
.box {
background: #333;
padding: 20px;
border-radius: 6px;
}
</style>
Custom Column Sizes
grid-template-columns: 200px 1fr 2fr;
- 200px = fixed
- 1fr = one equal part
- 2fr = double the size of 1fr
Using Auto-Fill (Responsive Grids)
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
This makes the grid automatically fit as many cards as possible.
Grid Rows
grid-template-rows: 100px 100px;
Placing Specific Items
.item1 {
grid-column: 1 / 3; /* spans 2 columns */
}
.item2 {
grid-row: 1 / 3; /* spans 2 rows */
}
Full Example — Dashboard Layout
.container {
display: grid;
grid-template-columns: 200px 1fr 1fr;
grid-template-rows: 100px 1fr;
gap: 15px;
}
.header {
grid-column: 1 / 4;
background: #333;
}
.sidebar {
background: #222;
}
.card {
background: #333;
}
Grid vs Flexbox — Quick Comparison
- Use Flexbox for toolbars, navbars, single-row layouts
- Use Grid for dashboards, galleries, multi-row layouts
Why Grid Is Powerful
- Build complex layouts easily
- Responsive without media queries
- Cleaner code
What’s Next?
Next you’ll learn error handling in Batch — catching, preventing, and avoiding script failures.