CSS Flexbox (Flexible Box Layout) is a one-dimensional layout system that helps developers align and distribute space among items in a container efficiently. This guide takes you from zero to hero with Flexbox properties, code examples, and illustrations.
1. What is Flexbox?
Flexbox is a layout module in CSS that provides an easy and clean way to arrange items within a container, even when their size is unknown or dynamic. It works in one direction—either as a row or a column.
To use Flexbox, define a container as a flex container:
CSS Example
.container {
display: flex;
}
2. Main Axis vs Cross Axis
The main axis is the primary axis along which flex items are laid out. It depends on the 'flex-direction' property. The cross axis runs perpendicular to the main axis.
3. flex-direction
This property defines the direction of the main axis. It can take the following values:
row (default): Items placed left to right
row-reverse: Items placed right to left
column: Items placed top to bottom
column-reverse: Items placed bottom to top
Example
.container {
display: flex;
flex-direction: row;
}
4. justify-content
This property aligns flex items along the main axis. Values include:
flex-start
flex-end
center
space-between
space-around
space-evenly
Example
.container {
justify-content: center;
}
5. align-items
This property aligns items along the cross axis:
flex-start
flex-end
center
baseline
stretch
Example
.container {
align-items: stretch;
}
6. align-content
Used when multiple lines of flex items exist. It aligns lines across the cross axis:
flex-start
flex-end
center
space-between
space-around
stretch
7. flex-wrap
By default, items try to fit in one line. Use flex-wrap to make them wrap:
nowrap (default)
wrap
wrap-reverse
Example
.container {
flex-wrap: wrap;
}
8. align-self
This allows individual items to override align-items setting for their own alignment.
Example
.item {
align-self: flex-end;
}
9. gap (row-gap, column-gap)
The gap property adds spacing between flex items without using margins.
Example
.container {
display: flex;
gap: 20px;
}
10. order
This property defines the order of flex items. Lower values appear first.
Example
.item1 { order: 2; }
.item2 { order: 1; }
11. flex-grow, flex-shrink, flex-basis
These three properties define how a flex item behaves in available space:
Shortcut
12. Practical Example
Example combining all properties:
.container {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
}
.item {
flex: 1 1 200px;
margin: 10px;
background-color: lightblue;
text-align: center;
}
Conclusion
Flexbox simplifies complex layouts and allows responsive design with minimal code. Once mastered, it becomes an essential part of every web developer’s toolkit.