CSS Flexbox (Flexible Box) is a layout model that makes it easy to design flexible and responsive layouts without using floats or positioning.
1. Basic Flexbox Structure
Flexbox consists of a flex container and flex items.
.container {
display: flex; /* Enables flexbox */
}
2. Main Flexbox Properties
- display: flex; → Activates flexbox
- flex-direction: row | column | row-reverse | column-reverse
- justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly
- align-items: flex-start | flex-end | center | stretch | baseline
- flex-wrap: nowrap | wrap | wrap-reverse
- align-content: flex-start | flex-end | center | space-between | space-around | stretch
3. Flex Direction
Controls the **main axis** direction.
.container {
display: flex;
flex-direction: row; /* Default: items placed in a row */
}
4. Justify Content
Aligns items along the **main axis**.
.container {
display: flex;
justify-content: center; /* Centers items horizontally */
}
5. Align Items
Aligns items along the cross axis.
.container {
display: flex;
align-items: center; /* Centers items vertically */
}
6. Flex Wrap
Controls whether flex items should wrap.
.container {
display: flex;
flex-wrap: wrap; /* Items wrap to the next line */
}
7. Align Content
Aligns multiple rows of flex items.
.container {
display: flex;
flex-wrap: wrap;
align-content: space-between;
}
8. Individual Flex Items
Control item sizes using flex-grow, flex-shrink, and flex-basis.
.item {
flex: 1; /* Equal width for all items */
}
9. Flexbox Example: Centering Content
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
Conclusion
CSS Flexbox makes layouts flexible and responsive. Mastering it will help in building modern web designs.