Home >Web Front-end >CSS Tutorial >How to Align Elements Left and Center in Flexbox Without Absolute Positioning?
Problem:
Align child elements within a flexbox container, with one element centered and the other aligned to the left.
Code:
#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; }
Issue:
Using margin-right: auto pushes the centered element off-center.
Solution without Absolute Positioning:
Add a third empty element:
<div class="parent"> <div class="left">Left</div> <div class="center">Center</div> <div class="right"></div> </div>
Apply the following styles:
.parent { display: flex; } .left, .right { flex: 1; }
Explanation:
Both left and right are set to grow (flex: 1), evenly distributing the available space. Since the empty right element has the same width as left, the center element remains perfectly centered.
Benefits of this Solution:
The above is the detailed content of How to Align Elements Left and Center in Flexbox Without Absolute Positioning?. For more information, please follow other related articles on the PHP Chinese website!