How to place the last flex item at the end of a row?

Jun 7, 2024

In this article, we will learn to position the last element on the right of a flexbox row.

Lets say, you have a flex container that contains three elements.

<div class="container">
  <h1>Elon Musk</h1>
  <div>@elonmusk</div>
  <button>Follow</button>
</div>

Output:

Before adding "margin-left: auto" on the last flex element

And you want to place the first two elements on the left and the last element on the right, like below:

After adding "margin-left: auto" on the last flex element

We achieve this by adding margin-left: auto on the last flex element in our CSS.

.container {
  display: flex;
  flex-direction: row;
}

button {
  margin-left: auto;
}

Explanation

In the first image above, notice there is a lot of free space remaining after the follow button.

But after adding margin-left: auto on the last element, flexbox adds that remaining space on the left side of the last element as margin, thus making the element appear on the right.

Likewise, if you apply margin-left: auto on the second element, the username and the button will be pused to the right. And if you apply margin-right: auto on the second element, the follow button will be pushed to the right.