CSS Flexbox
Flexbox is a layout mode that places the children of a container as flexible items. The items line up in a row by default and can wrap to a new line.
The list becomes a row
One rule turns the list into a flex container. Its three items line up side by side in a single row.
ul {
display: flex;
}A column instead of a row
The flex-direction value column stacks the items downwards. The items now share a left edge instead of a top edge.
ul {
display: flex;
flex-direction: column;
}Items wrap to a new line
The list is 300 pixels wide and each item is 120 pixels wide. Two items fill the row, so the third item wraps below.
ul {
display: flex;
flex-wrap: wrap;
width: 300px;
}
li {
width: 120px;
}Example
ul {
display: flex;
flex-wrap: wrap;
width: 300px;
}
li {
width: 120px;
}Key points
- display: flex turns a container into a flex container.
- The children of a flex container become flex items on their own.
- Items sit in one row by default, each sized by its content.
- flex-direction sets the direction the items line up in.
- flex-wrap lets items move to a new line when a row fills up.
- The main axis follows the layout direction, and the cross axis runs across it.
In this example, the list becomes a flex container with wrapping on. Its width is fixed at 300 pixels. Each item is 120 pixels wide, so two items sit on the first row. The third item wraps to a second row below them.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does display: flex do to the children of a container?