What I want as a result:
I have three elements in a container that is a display: flex
I want the left item to be aligned to the left, and the right item to the right. With the center item aligned in the center.
space-between
is not the fix. It is not the solution I am looking for. This is because the elements are differing widths. Even with differing widths, I still want the middle element to be centered.
This could be fixed with a wrapper. and then put a flex: 1
on the wrappers, then within those wrappers, have the elements themselves. Again, this is not the fix I am looking for. I cannot use wrappers in my situation.
.parentContainer {
display: flex;
justify-content: center;
align-items: center;
}
.parentContainer > *{
background: red;
text-align: center;
}
<div class="parentContainer">
<div class="left">small</div>
<div class="middle">medium element here</div>
<div class="right">longer element is here too</div>
</div>
Make each item a (nested) flex container and add justify-content: center . Now each span element is a centered flex item. Use flex auto margins to shift the outer span s left and right.
To center our box we use the align-items property to align our item on the cross axis, which in this case is the block axis running vertically. We use justify-content to align the item on the main axis, which in this case is the inline axis running horizontally.
By default items start from the left if flex-direction is row , and from the top if flex-direction is column . You can change this behavior using justify-content to change the horizontal alignment, and align-items to change the vertical alignment.
All you need to do is add both justify-content: center and align-items:center and flex-direction:column to the Header's CSS rules. You can use this combination of flexbox properties to center any element, not just navbars. Images, divs, etc can all be absolutely centered within a parent element.
The primary way to achieve this layout – because it's clean and valid – is with flex: 1
on the items. That method is explained in the following post, but is also ruled out in this question.
An alternative method involves CSS absolute positioning:
.parentContainer {
display: flex;
justify-content: space-between;
position: relative;
}
.middle {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
/* non-essential decorative styles */
.parentContainer > * { background: orange; text-align: center; padding: 5px; }
p { text-align: center;}
p > span { background-color: aqua; padding: 5px; }
P > span:first-child { font-size: 1.5em; }
<div class="parentContainer">
<div class="left">small</div>
<div class="middle">medium element here</div>
<div class="right">longer element is here too</div>
</div>
<p>
<span>↑</span><br>
<span>true center</span>
</p>
This method is explained in the following posts:
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