【问题标题】:Center a flex item when its siblings have different widths [duplicate]当它的同级具有不同的宽度时,居中一个弹性项目[重复]
【发布时间】:2017-11-07 23:07:49
【问题描述】:
我知道 flexbox 为居中项目提供了一个很好的解决方案。但是当我有 3 个项目并且我希望中心(第 2 个)项目相对于窗口居中时,我遇到了一个问题,而不管其他 2 个项目的大小。
在我的笔中,您可以看到第二项“客户索引”偏离中心,因为右侧的内容大于左侧的内容。 我怎样才能强制它自己居中?
.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
【问题讨论】:
标签:
html
css
flexbox
centering
【解决方案1】:
一种方法是设置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>
【解决方案2】:
使用嵌套的弹性容器和auto 边距。
.flex-container {
display: flex;
}
.flex-item {
flex: 1;
display: flex;
justify-content: center;
}
.flex-item:first-child>span {
margin-right: auto;
}
.flex-item:last-child>span {
margin-left: auto;
}
/* non-essential */
.flex-item {
align-items: center;
border: 1px solid #ccc;
background-color: lightgreen;
height: 40px;
}
<div class="flex-container">
<div class="flex-item"><span>short</span></div>
<div class="flex-item"><span>medium</span></div>
<div class="flex-item"><span>lonnnnnnnnnnnnnnnnnnnng</span></div>
</div>
它是这样工作的:
- 顶级 div 是一个弹性容器。
- 现在每个子 div 都是一个弹性项目。
- 为每个项目分配
flex: 1,以便平均分配容器空间。
- 现在项目占用了行中的所有空间并且宽度相等。
- 使每个项目成为(嵌套的)弹性容器并添加
justify-content: center。
- 现在每个
span 元素都是居中的弹性项目。
- 使用 flex
auto 边距将外部 spans 左右移动。
您也可以放弃justify-content 并专门使用auto 边距。
但是justify-content 可以在这里工作,因为auto 边距始终具有优先权。来自规范:
8.1. Aligning with auto
margins
在通过justify-content 和align-self 对齐之前,任何
正的可用空间分配到该维度的自动边距。