:
šÆ 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
š¹ļø Flexbox Froggy (Game)
ā 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 |