๐งฉ CSS COURSE โ MODULE 8: FLEXBOX
๐ File: flexbox.md
๐งฉ Flexbox (Flexible Box Layout)
๐ Introduction
Flexbox is a modern CSS layout system used to arrange elements easily.
๐ It helps you:
- align items horizontally or vertically
- distribute space
- center elements easily
- build responsive layouts
๐ง 1. Flex Container
To use Flexbox, you start with a container:
.container {
display: flex;
}
โ This activates flex behavior
๐ฆ 2. Flex Direction
.container {
display: flex;
flex-direction: row;
}
Values:
rowโ left to right (default)columnโ top to bottomrow-reversecolumn-reverse
๐ 3. Justify Content (MAIN AXIS)
.container {
justify-content: center;
}
Controls horizontal alignment:
| Value | Effect |
|---|---|
| flex-start | left |
| flex-end | right |
| center | middle |
| space-between | spread |
| space-around | spacing |
๐ 4. Align Items (CROSS AXIS)
.container {
align-items: center;
}
Controls vertical alignment:
| Value | Effect |
|---|---|
| flex-start | top |
| flex-end | bottom |
| center | middle |
| stretch | full height |
๐ 5. Flex Wrap
.container {
flex-wrap: wrap;
}
Behavior:
- Items move to next line if needed
โก 6. Gap (Spacing)
.container {
gap: 20px;
}
โ Replaces margin hacks โ Cleaner spacing system
๐ง 7. Flex Items
Each child inside flex container is a flex item.
.item {
flex: 1;
}
Meaning:
- takes equal space
๐ 8. Flex Grow / Shrink
.item {
flex-grow: 1;
flex-shrink: 1;
}
Meaning:
- grow โ expand
- shrink โ reduce size
๐งฉ Real Example
<div class="container">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
</div>
.container {
display: flex;
justify-content: center;
align-items: center;
gap: 10px;
height: 200px;
}
.box {
background: blue;
color: white;
padding: 20px;
}
๐ฏ Center Anything (VERY IMPORTANT)
.container {
display: flex;
justify-content: center;
align-items: center;
}
โ This centers anything perfectly (horizontally + vertically)
โ ๏ธ Common Mistakes
- Forgetting
display: flexโ - Mixing flex with float โ
- Not understanding axes โ
- Overusing margins instead of gap โ
๐ง Flexbox Mental Model
Main Axis โ justify-content
Cross Axis โ align-items
๐งช Mini Exercise
Create:
- A navbar using flexbox
- Center a box perfectly
- A row of 3 cards with spacing
- A column layout with flex-direction