Direction and wrap

flex-direction

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 flex-direction property:


 





<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.
  • column stacks containers vertically from top to bottom.
  • row-reverse stacks from right to left, the opposite of row.
  • column-reverse stacks from bottom to top, the opposite of column.

flex-wrap

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 flex-wrap property:


 















<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.

The 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.
  • wrap allows child containers to create new lines when it is required by their styles.
  • wrap-reverse takes the behavior of wrap, but the new lines are created above the existing ones.

Practice

Buttons alignment

Align the buttons vertically:

  1. Fork your result of the Buttons task in the Box model article. You can also fork the prototype from the article.
  2. Wrap all buttons in a single flex parent container.
  3. 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:

  1. Fork the starting prototype. It includes the containers with the images and some necessary styles.
  2. Wrap all containers in a single flex parent container.
  3. Allow items in the flex container to create new lines using the flex-wrap property.
  4. Set the width of all child div containers to take half of the parent’s width using percentages.