Timestretch Timestretch - 5 months ago 18
CSS Question

Horizontally center flex item between 2 flex items of different widths

Say I have 3 divs displayed horizontally with

flexbox
:

| |-div1-| |-center-div-| |-wider-div-| |


And I want the center div to be aligned to the middle of the parent. How can I accomplish this?
justify-content
will center all 3 of the divs based the sum of all their widths, and applying
align-self: center
to the middle div does nothing because the align property manipulates positioning on the other axis.

Is there a responsive CSS solution, or should I resort to jQuery?



ul {
display: flex;
justify-content: center;
width: 100%;
background-color: purple;
}
li {
background-color: red;
border: 5px solid blue;
list-style: none;
}

<ul>
<li><a href = "#">short</a></li>
<li><a href = "#">want center</a></li>
<li><a href = "#">loooooooooooooooooong</a></li>
</ul>





Illustration of this problem:
https://jsfiddle.net/7w8mp8Lj/2/

Answer

You can set the first and last li to grow flex: 1, and set a as inline block and text align 1/2/3 li as right/center/left.

jsfiddle

ul {
    display: flex;
    justify-content: center;
    width: 100%;
    background-color: purple;
    list-style: none;
    padding: 0;
}
li:nth-child(1) {
    text-align: right;
    flex: 1;
}
li:nth-child(2) {
    text-align: center;
}
li:nth-child(3) {
    text-align: left;
    flex: 1;
}
li a {
    display: inline-block;
    background-color: red;
    border: 5px solid blue;
}
<ul>
    <li><a href="#">short</a></li>
    <li><a href="#">want center</a></li>
    <li><a href="#">loooooooooooooooooong</a></li>
</ul>