我知道 flexbox 为元素居中提供了一个很好的解决方案。但是,当我有 3 个元素并且我希望中心(第 2 个)元素相对于窗口居中时,我遇到了一个问题,而不管其他 2 个元素的大小如何。
在我的笔中,您可以看到第二项“Client Index”偏离中心,因为右侧的内容比左侧的内容大。 我怎样才能强制它居中?
.flex {
display: flex;
align-items: center;
justify-content: space-between;
}
<div class="flex">
<span style="font-size:12px;">small</span>
<span style="font-size:20px;">Client Index</span>
<span style="font-size:18px;">Lots of content that moves the center</span>
</div>
My Codepen
一种方法是设置 flex-grow: 1; flex-basis: 0
所以3列均匀分布,然后你可以将文本或内容居中。
我正在使用 text-align
使中间列居中。你也可以使用 display: flex; justify-content: center;
做同样的事情。
.flex {
display: flex;
align-items: center;
justify-content: space-between;
}
.flex > span {
flex: 1 0 0;
}
.flex > span:nth-child(2) {
text-align: center;
}
<div class="flex">
<span style="font-size:12px;">small</span>
<span style="font-size:20px;">Client Index</span>
<span style="font-size:18px;">Lots of content that moves the center</span>
</div>