Home > Article > Web Front-end > How to Center a Flex Item Among Siblings in Flexbox?
Centering a Flex Item When Surrounded by Other Flex Items
In Flexbox, aligning items is typically achieved by distributing free space in the container. Therefore, centering a single flex item among siblings is not possible unless the combined length of the siblings is equal on both sides.
One workaround is to wrap the surrounding flex items within their own containers. This allows for greater control over the space distribution and enables the centering of the h2 element. Consider the following modified HTML structure:
<code class="html"><div class="container"> <div> <span>I'm span 1</span> <span>I'm span 2</span> <span>I'm span 3</span> </div> <h2>I'm an h2</h2> <div> <span>I'm span 4</span> <span>I'm span 5</span> <span>I'm span 6</span> </div> </div></code>
With this modification, the CSS rules can be adjusted to align the the h2:
<code class="css">.container { display: flex; justify-content: center; align-items: center; border: 1px solid red; margin: 5px; padding: 5px; } .container > div { flex: 1 1 auto; text-align: center; } h2 { margin: auto; }</code>
By wrapping the spans in separate divs, the flexbox properties can be applied to control their individual size and alignment, ensuring that the h2 remains centered, regardless of the number of surrounding elements.
The above is the detailed content of How to Center a Flex Item Among Siblings in Flexbox?. For more information, please follow other related articles on the PHP Chinese website!