What Is CSS Grid?
CSS Grid is a two-dimensional layout system in CSS that allows you to design layouts using rows and columns at the same time.
It is best suited for entire page layouts and complex grid-based designs.
🧱 Basic Grid Setup
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}
This creates 3 equal columns with spacing.
✅ Why Use CSS Grid?
✔ Control rows AND columns
✔ Precise placement of items
✔ Clean layout code
✔ Better for complex designs
✔ Responsive layouts without media queries (in many cases)
🔑 Key Grid Properties
grid-template-columns
grid-template-rows
grid-area
grid-column
grid-row
gap
🧪 Simple Grid Example
.container {
display: grid;
grid-template-columns: 200px 1fr 200px;
}
.header { grid-column: 1 / -1; }
.sidebar { grid-column: 1 / 2; }
.content { grid-column: 2 / 3; }
✔ Easy page structure
✔ Clear layout logic
🔥 CSS Grid vs Flexbox
| Feature | CSS Grid | Flexbox |
|---|---|---|
| Dimension | 2D (rows + columns) | 1D (row OR column) |
| Best for | Page layouts | Components |
| Layout control | Precise placement | Content-based |
| Alignment | Both axes | Main axis focused |
| Responsive | Excellent | Excellent |
| Complexity | Handles complex layouts | Simpler layouts |
🧠 When to Use Which?
✔ Use CSS Grid when:
- Designing page layouts
- Working with rows and columns
- Creating dashboards or galleries
✔ Use Flexbox when:
- Aligning items in a single direction
- Navigation bars
- Buttons, cards, lists
🎯 Short Interview Answer
CSS Grid is a two-dimensional layout system that controls rows and columns, making it ideal for page-level layouts.
Flexbox is a one-dimensional layout system best for aligning items in a single row or column.
Both are complementary and often used together.
⭐ One-liner
Grid is for layout structure; Flexbox is for content alignment.