For an odd number of flex items I want the middle one to be in perfect center and other items just flow around it. The middle item has fixed width, all the rest are fluid and must stick to the middle item so the paddings are fixed.
/* CSS */
.flex-holder {
display: flex;
justify-content: center;
}
.middle-item {
width: 75px;
}
<!-- HTML -->
<ul class="flex-holder">
<li>Item 1</li>
<li>Some item</li>
<li class="middle-item">Middle</li>
<li>Very long text item</li>
<li>Test</li>
</ul>
Is it actually possible with flexbox? If no, please suggest another solution.
One solution would be to use position: absolute
on middle element and center it with transform: translate()
but there will be overflow of elements on small window size which you can fix with media queries.
.flex-holder {
display: flex;
justify-content: space-around;
position: relative;
list-style: none;
padding: 0;
}
.middle-item {
width: 75px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
<ul class="flex-holder">
<li>Item 1</li>
<li>Some item</li>
<li class="middle-item">Middle</li>
<li>Very long text item</li>
<li>Test</li>
</ul>
Another solution that will get result close to desired result is to wrap li
's left and right of middle li in ul
's and set flex: 1
on them so they take equal size and set middle div always in center.
ul, .wrap {
display: flex;
justify-content: space-around;
position: relative;
list-style: none;
flex: 1;
padding: 0;
}
.middle-item {
width: 75px;
background: lightblue;
text-align: center;
}
<ul class="flex-holder">
<li class="wrap">
<ul>
<li>Item 1</li>
<li>Some item</li>
</ul>
</li>
<li class="middle-item">Middle</li>
<li class="wrap">
<ul>
<li>Very long text item</li>
<li>Test</li>
</ul>
</li>
</ul>
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