CSS Flexbox Guide: Mastering Layouts
Flexbox is a powerful CSS module that makes it easy to design flexible, responsive layouts. In this guide, we'll cover the fundamentals, container and item properties, and walk through common patterns with live examples.
1. Flex Container Basics
To start using Flexbox, define a container with display: flex (or inline-flex).
.container {
display: flex;
}
This turns all direct children into flex items.
2. Container Properties
flex-direction
Controls the main axis direction.
.container {
flex-direction: row; /* row | row-reverse | column | column-reverse */
}
justify-content
Aligns items along the main axis.
.container {
justify-content: center; /* flex-start | flex-end | center | space-between | space-around | space-evenly */
}
align-items
Aligns items along the cross axis.
.container {
align-items: stretch; /* flex-start | flex-end | center | baseline | stretch */
}
3. Flex Item Properties
flex-grow, flex-shrink, flex-basis
Shorthand flex controls how items grow or shrink.
.item {
flex: 1 1 200px; /* flex-grow | flex-shrink | flex-basis */
}
4. Common Layout Patterns
- Centering both axes:
justify-content:center; align-items:center; - Space between items:
justify-content:space-between; - Wrapping rows:
flex-wrap:wrap;
5. Interactive Flexbox Demo
Use the controls below to see how different properties affect the layout.
Item 1
Item 2
Item 3