Lesson 9: Flexbox Fundamentals
π¦ Lesson 9: Flexbox Fundamentals
Flexbox is a powerful layout module in CSS that makes it easy to design flexible and responsive layout structures β especially when you need to align items in a row or column.
1. The Flex Container
To activate Flexbox, apply display: flex; to a container element. This makes all its direct children flexible items.
.container {
display: flex;
}
2. Direction of Items: flex-direction
You control the direction of the layout with flex-direction. It can be:
- row β horizontal (default)
- row-reverse β horizontal, reversed
- column β vertical
- column-reverse β vertical, reversed
.container {
display: flex;
flex-direction: row;
}
3. Main Axis Alignment: justify-content
Controls spacing and alignment along the main axis:
flex-startβ start of containercenterβ center of containerspace-betweenβ even gapsspace-aroundβ equal space around itemsspace-evenlyβ equal space everywhere
.container {
justify-content: space-between;
}
4. Cross Axis Alignment: align-items
Aligns items vertically (if flex-direction: row):
stretchβ (default) fill the containerflex-startβ top of containercenterβ vertically centeredflex-endβ bottom of container
.container {
align-items: center;
}
5. Spacing Items: gap
Add spacing between flex items using gap:
.container {
gap: 16px;
}
6. Controlling Item Growth
You can control how items grow or shrink with:
flex-growβ defines how much a flex item should growflex-shrinkβ defines how items shrink if neededflex-basisβ initial size of the item before growing/shrinking
.item {
flex-grow: 1;
flex-shrink: 1;
flex-basis: 200px;
}
7. Wrap It Up: flex-wrap
By default, Flexbox does not wrap. Use flex-wrap if items overflow.
.container {
flex-wrap: wrap;
}
β Recap
- Start with
display: flex; - Choose direction with
flex-direction - Align items using
justify-contentandalign-items - Use
gapfor spacing - Control item sizes with
flex-grow,flex-shrink, andflex-basis
Flexbox is a layout cheat code. Get used to it, and layout hell becomes layout heaven. Up next, weβll dive into Flexbox Alignment and Wrapping .