:
🎯 CSS Flexbox – The Complete Guide for Beginners
Flexbox (short for Flexible Box Layout) is a CSS layout model that makes it easy to design responsive, one-dimensional layouts (either rows or columns) that adjust automatically to different screen sizes.
✅ Use Flexbox when you want elements to align, grow, shrink, or wrap inside a container — without floats or positioning hacks.
🧱 Basic Flexbox Structure
html
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
css
.container {
display: flex;
}
🧰 Main Flexbox Properties
🔹 display: flex
Turns the container into a flex context.
🔹 flex-direction
Controls the main axis (row or column):
css
.container {
flex-direction: row; /* default */
flex-direction: column;
flex-direction: row-reverse;
flex-direction: column-reverse;
}
🔹 justify-content
Aligns items along the main axis (left → right):
css
.container {
justify-content: flex-start; /* default */
justify-content: center;
justify-content: flex-end;
justify-content: space-between;
justify-content: space-around;
justify-content: space-evenly;
}
🔹 align-items
Aligns items along the cross axis (top ↕ bottom):
css
.container {
align-items: stretch; /* default */
align-items: center;
align-items: flex-start;
align-items: flex-end;
align-items: baseline;
}
🔹 flex-wrap
Allows items to wrap onto multiple lines:
css
.container {
flex-wrap: nowrap; /* default */
flex-wrap: wrap;
flex-wrap: wrap-reverse;
}
🔹 gap
Adds space between items:
css
.container {
gap: 20px;
}
📦 Flex Item Properties
🔸 flex: [grow] [shrink] [basis]
css
.item {
flex: 1; /* grow = 1, shrink = 1, basis = 0 */
}
Or full syntax:
css
.item {
flex: 1 1 200px;
}
🔸 align-self
Override alignment for individual items:
css
.item {
align-self: center;
}
🔸 order
Rearranges item order without changing HTML:
css
.item {
order: 2;
}
🧪 Example Layout
css
.container {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 10px;
}
📱 Responsive Flexbox Example
css
@media (max-width: 600px) {
.container {
flex-direction: column;
align-items: stretch;
}
}
🧠 Flexbox vs Grid
Feature | Flexbox | CSS Grid |
---|---|---|
Layout direction | One-dimensional (row or column) | Two-dimensional (rows + columns) |
Content-driven | ✅ | ❌ |
Layout-driven | ❌ | ✅ |
Use case | Navbars, toolbars, cards | Page layouts, galleries |
🧪 Practice Tools
✅ Summary
Property | What It Does |
---|---|
display: flex | Activates Flexbox |
flex-direction | Sets main axis |
justify-content | Aligns items on main axis |
align-items | Aligns items on cross axis |
flex-wrap | Allows wrapping |
gap | Adds spacing between items |