Direction and wrap
As you’ve seen in the previous article, containers are stacked horizontally in a flex parent by default:
You can change the way child containers are stacked with the
<div style="display: flex; flex-direction: column;"> <div style="background-color: #E2E8F0; padding: 12px;">One</div> <div style="background-color: #CBD5E0; padding: 12px;">Two</div> <div style="background-color: #718096; padding: 12px;">Three</div> </div>
The available values are:
row, the default value, stacks containers horizontally from left to right.
columnstacks containers vertically from top to bottom.
row-reversestacks from right to left, the opposite of
column-reversestacks from bottom to top, the opposite of
By default, all containers inside a flex container will do whatever it takes to fit into one stack and the will never create a new one:
You can allow the containers to create new lines with the
<div style="display: flex; flex-wrap: wrap;"> <div style="background-color: #A0AEC0; width: 25%;"> One </div> <div style="background-color: #CBD5E0; width: 25%; "> Two </div> <div style="background-color: #E2E8F0; width: 25%;"> Three </div> <div style="background-color: #E2E8F0; width: 25%;"> Four </div> <!--...--> </div>
All child containers have width set to 25%, so only four of them can fit into one line. With
flex-wrap: wrap applied to the flex parent container, the fifth item is allowed to create a new a line.
flex-wrap property can have one of three values:
nowrap, the default value, prevents child containers from creating new lines by forcing them to fit into a single one.
wrapallows child containers to create new lines when it is required by their styles.
wrap-reversetakes the behavior of
wrap, but the new lines are created above the existing ones.
Align the buttons vertically:
- Fork your result of the Buttons task in the Box model article. You can also fork the prototype from the article.
- Wrap all buttons in a single flex parent container.
- Apply vertical direction to the flex container.
You will learn why the buttons take full width in a flex container with vertical direction by default in the next article.
Create a two-column image gallery:
- Fork the starting prototype. It includes the containers with the images and some necessary styles.
- Wrap all containers in a single flex parent container.
- Allow items in the flex container to create new lines using the
- Set the width of all child
divcontainers to take half of the parent’s width using percentages.