Align elements left and center using Flexbox
P粉545682500
2023-08-27 21:54:23
<p>I'm using Flexbox to align my child elements. What I want to do is center one element and align the other element to the left. Normally I would use <code>margin-right: auto</code> to set the left element. The problem is pushing the center element away from the center. Is this possible without using absolute positioning? </p>
<p><strong>HTML and CSS</strong></p>
<p><br /></p>
<pre class="brush:css;toolbar:false;">#parent {
align-items: center;
border: 1px solid black;
display: flex;
justify-content: center;
margin: 0 auto;
width: 500px;
}
#left {
margin-right: auto;
}
#center {
margin: auto;
}</pre>
<pre class="brush:html;toolbar:false;"><div id="parent">
<span id="left">Left</span>
<span id="center">Center</span>
</div></pre>
<p><br /></p>
Add a third empty element:
and the following styles:
Only the left and the right will grow, and due to the fact...
...The center element will always be perfectly centered.
In my opinion this is much better than the accepted answer because you don't have to copy the left content to the right and hide it to get the same width on both sides, it just magically happens (flexbox is amazing).
Actual operation:
EDIT: See Solo's answer below, which is a better solution.
The idea behind flexbox is to provide a framework for easily aligning elements with variable dimensions within a container. Therefore, it makes no sense to provide a layout that completely ignores the width of an element. Essentially, this is what absolute positioning is for, as it takes the element out of the normal flow.
As far as I know there is no good way to do this without using
position:absolute;
so I recommend using it...but if you really don't want to Doing this, or being unable to use absolute positioning, then I guess you can use one of the following workarounds.If you know the exact width of the "left" div, then you can change
justify-content
toflex-start
(left) and then like Align the "centered" div like this:If you don't know the width, then you can copy "Left" on the right, use
justify-content: space- Between;
, and then hide the new right element: To be clear, this is really, really ugly... it's better to use absolute positioning than copy the content. :-)