CSS Grid and Flexbox Layouts
By Rahul Balmiki
Modern web design requires flexible and efficient layout techniques. CSS offers two powerful
layout systems: Flexbox and Grid. Both help you align, distribute, and position elements in
a responsive way — but they serve different purposes.
🔹 What is Flexbox?
Flexbox (Flexible Box Layout) is a one-dimensional layout system — used to arrange items
in a row or column.
✅ When to Use Flexbox:
● You need to align items in a single row or column
● You want dynamic spacing between elements
● You need to align elements vertically or horizontally with ease
📌 Basic Syntax:
css
CopyEdit
.container {
display: flex;
justify-content: center; /* Aligns items horizontally */
align-items: center; /* Aligns items vertically */
}
🧪 Flexbox Example:
html
CopyEdit
<div class="container">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
</div>
<style>
.container {
display: flex;
justify-content: space-between;
background-color: #ddd;
padding: 10px;
}
.box {
background-color: steelblue;
color: white;
padding: 20px;
margin: 5px;
}
</style>
🔸 What is CSS Grid?
Grid is a two-dimensional layout system — it allows you to align items both horizontally
and vertically in a grid format (rows and columns).
✅ When to Use Grid:
● You want to design a full web page layout
● You need both row and column control
● You want precise control over grid areas
📌 Basic Syntax:
css
CopyEdit
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr 1fr; /* 3 equal columns */
gap: 10px;
}
🧪 Grid Example:
html
CopyEdit
<div class="grid-container">
<div class="grid-item">A</div>
<div class="grid-item">B</div>
<div class="grid-item">C</div>
<div class="grid-item">D</div>
</div>
<style>
.grid-container {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 20px;
background-color: #eee;
padding: 20px;
}
.grid-item {
background-color: #2196F3;
color: white;
padding: 30px;
text-align: center;
}
</style>
🆚 Flexbox vs Grid:
Feature Flexbox Grid
Layout Type One-dimensional (row/column) Two-dimensional (rows + columns)
Use Case Components inside a section Whole page layouts
Alignment Easier for single-axis More control over structure
✅ Which One Should You Use?
● Use Flexbox for small components, navbars, or card layouts
● Use Grid for complex layouts with rows and columns
● Combine both for maximum flexibility in modern designs