在不同宽度的2个弹性项目之间水平居中柔性项目 [英] Horizontally center flex item between 2 flex items of different widths
问题描述
说明我有3个div水平显示 flexbox
:
| | -div1- | | -center-div- | | -wider-div- | |
我想让中心div与父对象中心对齐。我该如何做到这一点? justify-content
会根据所有3个div的宽度,以及应用 align-self:center
到中间div没有什么作用,因为align属性操作另一个轴上的定位。
是否有响应式CSS解决方案,或者应该使用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 =#>短< / a>< / li> < li>< a href =#>想要中心< / a>< / li> < li>< a href =#> loooooooooooooooooong< / a>< / li>< / ul>
>
此问题的说明:
https ://jsfiddle.net/7w8mp8Lj/2/解决方案您可以设置第一个和最后一个
li
生长flex:1
,并将a
https://jsfiddle.net/nm9dywjx/ =nofollow> jsfiddle
ul {显示:flex; justify-content:center; width:100%;背景颜色:紫色; list-style:none; padding:0;} li:nth-child(1){text-align:right; flex:1;} li:nth-child(2){text-align:center;} li:nth-child flex:1;} li a {display:inline-block; background-color:red; border:5px solid blue;}
< ul& < li>< a href =#>短< / a>< / li> < li>< a href =#>想要中心< / a>< / li> < li>< a href =#> loooooooooooooooooong< / a>< / li>< / ul>
>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 applyingalign-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 growflex: 1
, and seta
as inline block and text align 1/2/3li
as right/center/left.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>
这篇关于在不同宽度的2个弹性项目之间水平居中柔性项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文