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/
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>
Here's a flex method that perfectly centers the middle item with:
ul {
display: flex;
padding: 0;
}
li {
display: flex;
justify-content: center;
flex: 1;
background-color: red;
border: 2px solid blue;
}
li:first-child > a {
margin-right: auto;
}
li:last-child > a {
margin-left: auto;
}
<ul>
<li>
<a href="#">short</a>
</li>
<li>
<a href="#">want center</a>
</li>
<li>
<a href="#">loooooooooooooooooong</a>
</li>
</ul>
Here's how it works:
ul
is the primary flex container.li
flex item is given flex: 1
for an equal distribution of container space.li
s are consuming all space in the row and are equal width.li
a flex container and add justify-content: center
auto
margins to shift the outer anchors left and right.You can use absolute positioning to take the non-centered items out-of-flow, so that they won't affect the centering.
ul {
display: flex;
justify-content: center;
background-color: purple;
padding: 0;
list-style: none;
}
li {
position: relative;
}
li > a {
display: block;
background-color: red;
border: 5px solid blue;
}
li:first-child > a {
position: absolute;
right: 0;
}
li:last-child > a {
position: absolute;
left: 0;
}
<ul>
<li><a href="#">short</a></li>
<li><a href="#">want center</a></li>
<li><a href="#">loooooooooooooooooong</a></li>
</ul>
However, note you will lose flexibility because absolutely-positioned children of a flex container do not participate in flex layout (except in the reordering step).
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