Home >Web Front-end >CSS Tutorial >How to Right-Align a Flexbox Item Using Only `margin-left: auto`?
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!