P粉5613239752023-08-28 20:51:28
Add a third empty element:
<div class="parent"> <div class="left">Left</div> <div class="center">Center</div> <div class="right"></div> </div>
and the following styles:
.parent { display: flex; } .left, .right { flex: 1; }
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).
.parent { display: flex; } .left, .right { flex: 1; } /* Styles for demonstration */ .parent { padding: 5px; border: 2px solid #000; } .left, .right { padding: 3px; border: 2px solid red; } .center { margin: 0 3px; padding: 3px; border: 2px solid blue; }
<div class="parent"> <div class="left">Left</div> <div class="center">Center</div> <div class="right"></div> </div>
P粉8999507202023-08-28 20:09:58
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
to flex-start
(left) and then like Align the "centered" div like this:
#center { position: relative; margin: auto; left: -{half width of left div}px; }
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. :-)
#parent {
align-items: center;
border: 1px solid black;
display: flex;
justify-content: space-between;
margin: 0 auto;
width: 500px;
}
#right {
opacity: 0;
}
<div id="parent">
<span id="left">Left</span>
<span id="center">Center</span>
<span id="right">Left</span>
</div>