I'm using flexbox to align my child elements. What I'd like to do is center one element and leave the other aligned to the very left. Normally I would just set the left element using margin-right: auto
. The problem is that pushes the center element off center. Is this possible without using absolute positioning?
HTML & CSS
#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; }
<div id="parent"> <span id="left">Left</span> <span id="center">Center</span> </div>
The flex columns can be aligned left or right by using the align-content property in the flex container class. The align-content property changes the behavior of the flex-wrap property. It aligns flex lines. It is used to specify the alignment between the lines inside a flexible container.
If we change our flex-direction to column, align-items and align-self will align the items to the left and right. You can try this out in the example below, which has a flex container with flex-direction: column yet otherwise is exactly the same as the previous example.
The align-content property is a sub-property of the Flexible Box Layout module. It helps to align a flex container's lines within it when there is extra space in the cross-axis, similar to how justify-content aligns individual items within the main-axis.
align-items and justify-content are the important properties to absolutely center text horizontally and vertically. Horizontally centering is managed by the justify-content property and vertical centering by align-items.
Add third empty element:
<div class="parent"> <div class="left">Left</div> <div class="center">Center</div> <div class="right"></div> </div>
And the following style:
.parent { display: flex; } .left, .right { flex: 1; }
Only left and right are set to grow and thanks to the facts that...
...center element will always be perfectly centered.
This is much better than accepted answer in my opinion because you do not have to copy left content to right and hide it to get same width for both sides, it just magically happens (flexbox is magical).
.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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With