Achieving precise item alignment is a common challenge in web design. Flexbox offers a powerful solution, but aligning items in specific configurations can be tricky. This article explores a common scenario where one item needs to be aligned right amidst other flex items.
Consider a flex container with three child items arranged side by side. The desired result is to have the first two items aligned left and the third item aligned right. The following HTML and CSS represent the initial setup:
<div class="wrap"> <div>One</div> <div>Two</div> <div>Three</div> </div>
.wrap { display: flex; justify-content: space-between; }
Flexbox provides a simple solution to this problem: setting margin-left: auto on the last child item. From the flex specification:
One use of auto margins in the main axis is to separate flex items into distinct "groups". This is exemplified by the common UI pattern of a single bar of actions, some of which are aligned on the left and others aligned on the right.
Applying margin-left: auto to the last child item in our example results in the desired alignment:
.wrap div:last-child { margin-left: auto; }
With this revised CSS, the resulting HTML and CSS code snippet yields the desired alignment, with the first two items aligned left and the third item aligned right within the flex container:
<div class="wrap"> <div>One</div> <div>Two</div> <div>Three</div> </div>
.wrap { display: flex; justify-content: space-between; } .wrap div:last-child { margin-left: auto; }
The above is the detailed content of How to Right-Align a Single Item in a Flexbox Container?. For more information, please follow other related articles on the PHP Chinese website!