Home >Web Front-end >CSS Tutorial >How to Center a Middle Item in a Horizontal Layout with Unequal Sibling Widths?
Maintaining Center Alignment for Middle Item with Varied Sibling Widths
This question addresses the challenge of centering a middle item within a horizontal layout when the width of its side items may vary. The desired effect is to ensure that the middle item remains centered even when the side items are of unequal size.
To achieve this, a nested flexbox approach is employed. The following CSS rules form the core of the solution:
.container { display: flex; } .box { flex: 1; display: flex; justify-content: center; } .box:first-child > div { margin-right: auto; } .box:last-child > div { margin-left: auto; }
Within the container, each box is given flex of 1, ensuring they share the available space proportionally. Each box is then displayed as a flex container with justify-content: center to center its content.
For the first box, a right margin is applied to its child element using margin-right: auto, and conversely, a left margin is applied to the last box's child element using margin-left: auto. This allows the margins to grow automatically, pushing the contents to their respective edges, effectively aligning the middle box in the center.
This solution achieves the desired effect, ensuring the middle item remains centered regardless of the widths of its sibling boxes. It is a pure CSS solution that requires no additional scripting or absolute positioning.
The above is the detailed content of How to Center a Middle Item in a Horizontal Layout with Unequal Sibling Widths?. For more information, please follow other related articles on the PHP Chinese website!