当兄弟元素的宽度不同时,如何使一个 flex 子项居中?

12

我知道 flexbox 提供了一个很好的居中方案。但是当我有3个项目并且我想让中间(第二个)项目相对于窗口居中时,我遇到了问题,而不考虑其他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>

我的Codepen

2个回答

12
一种方法是设置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>


3
使用嵌套的 flex 容器和 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 是一个 flex 容器。
  • 每个子 div 现在都是一个 flex 项。
  • 为了平均分配容器空间,给每个项目都添加 flex: 1
  • 现在,这些项目正在消耗行中的所有空间,并且宽度相等。
  • 将每个项目设为(嵌套的) flex 容器,并添加 justify-content: center
  • 现在,每个 span 元素都是一个居中的 flex 项。
  • 使用 flex 的 auto 边距将外部的 span 左右移动。

您也可以放弃使用 justify-content,而仅使用 auto 边距。

但是,在这里使用 justify-content 可以工作,因为 auto 边距始终具有优先级。来自规范:

8.1. 使用 auto 外边距对齐

在通过 justify-contentalign-self 进行对齐之前,任何正的自由空间都将在该维度上分配给自动外边距。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接