CSS Grid and Flexbox are modern layout systems in CSS, but they serve different purposes:
1️⃣ CSS Grid
- Two-dimensional layout → controls rows and columns.
- Ideal for complex layouts where you need to place items both horizontally and vertically.
- Uses grid containers and grid items.
Example:
.container {
display: grid;
grid-template-columns: 1fr 2fr 1fr; /* 3 columns */
grid-template-rows: 100px 200px; /* 2 rows */
gap: 10px;
}
.item {
background-color: lightblue;
}
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
</div>
✅ Items are placed in a grid layout, easy to control both row and column positions.
2️⃣ Flexbox
- One-dimensional layout → controls either a row or a column at a time.
- Ideal for aligning and distributing space among items in a container.
- Simple and perfect for components, navbars, lists.
Example:
.container {
display: flex;
justify-content: space-between; /* horizontal alignment */
align-items: center; /* vertical alignment */
}
🔹 Key Differences
| Feature | Flexbox | CSS Grid |
|---|---|---|
| Dimension | 1D (row or column) | 2D (rows + columns) |
| Alignment | Align items along single axis | Align items along both axes |
| Use Case | Component-level layout | Page-level / complex layout |
| Ordering | Easy to reorder items | Grid areas for precise placement |
💡 In Short
- Use Flexbox → for simple, one-dimensional layouts like navbars, buttons, lists.
- Use CSS Grid → for complex, two-dimensional layouts like dashboards, galleries, full-page layouts.