Home >Web Front-end >CSS Tutorial >How to Right-Align a Flexbox Item Using Only `margin-left: auto`?

How to Right-Align a Flexbox Item Using Only `margin-left: auto`?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-11 18:58:15919browse

How to Right-Align a Flexbox Item Using Only `margin-left: auto`?

How to Align One Item Right with Flexbox

Problem:

In the provided fiddle, aligning the third item to the right using flexbox appears challenging. The initial code aligns all three items to the left, while floating is used to align the last item to the right in the desired result.

Solution:

Utilizing the property "margin-left: auto" on the third child of the flex container effortlessly aligns it to the right. This technique leverages the auto margins feature in flexbox, which enables the distribution of flex items into distinct groups. By specifying margin-left: auto on the final flex child, it automatically adjusts its position to align it to the right side of the container.

Updated Code:

The following updated CSS snippet aligns the third item to the right using flexbox:

.wrap div:last-child {
  margin-left: auto;
}

The updated fiddle demonstrates the successful alignment of elements using flexbox:

<div class="wrap">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</div>
.wrap {
  display: flex;
  background: #ccc;
  width: 100%;
  justify-content: space-between;
}
.wrap div:last-child {
  margin-left: auto;
}

The above is the detailed content of How to Right-Align a Flexbox Item Using Only `margin-left: auto`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn