Flex-direction

In this lesson, we will learn the different flex-direction settings to confidently use both horizontal and vertical Flexbox containers. We will introduce the concepts of the main-axis and cross-axis to think about Flexbox layouts on a different level.

Setting the main and cross axes using flex-direction

Flexbox uses flex-direction to set both the main axis and the cross axis. The flex-direction property also sets the order in which flex-items flow inside the flex container.

We have four possible values for the flex-direction property:

  • row: this is the default value, you don’t need to set it manually. Elements flow from left to right. The main axis is horizontal, the cross axis is vertical.
  • row-reverse: Elements flow from right to left. The main axis is horizontal, and the cross axis is vertical just like in the case of the row value.
  • column: Elements flow from top to bottom. The main axis is vertical, and the cross axis is horizontal.
  • column-reverse: Elements flow from bottom to top. The main axis is vertical, the cross axis is horizontal.

Let’s see the four settings in an example. Let’s create three flex-items inside a flex container.

<div class="flex-container">
  <div class="flex-item">First</div>
  <div class="flex-item">Second</div>
  <div class="flex-item">Third</div>
</div>

Let’s set the container and item sizes to help us focus on the effect of flex-direction:

.flex-container {
  display: flex;
  width: 500px;
  background-color: lightgreen;
}

.flex-item {
  width: 100px;
  margin: 10px;
  padding: 5px;
  background-color: dodgerblue;
  border: 1px solid black;
}

Get hands-on with 1000+ tech skills courses.