CSS: How to position last flex element at the end of its container

In this short lesson, I will show a simple technique on how to position a child of a flex container at the end of the container, regardless of the flex direction. Here is the result that we are striving for:

In order to achieve this, you simply need to add margin-[opposite-direction-of-the-placement]: auto . In our case, we want the element to be placed at the right end of the container, so we add it margin-left: auto .

Here is the full code. Note that the solution is applicable for vertical positioning too, so if you have flex-direction: column you can place a child at the bottom of the container by adding margin-top: auto to it.

.flex-container {
  border: 1px solid blue;
  padding:20px;
  margin-top: 20px;
  display: flex
}

.flex-child {
  font-size:14px;
  border:1px solid red;
  margin: 0 10px;
}

/* Place this flex element at the end of the container  */
.flex-child.position-end {
  margin-left: auto;
}

Link to Codepen