使用justify-content: center无法使文本居中

13

我有一个使用display: flex

,它的内容在水平和垂直方向上都是居中的。

中的内容过长时,会自动换行。但这种情况下对齐方式会被打破,可以在代码片段中看到。

如果添加text-align: center,则可以正确地显示。但为什么没有text-align: center就不能居中对齐呢?

.box{
  width: 100px;
  height: 100px;
  background-color: lightgreen;
  margin: 10px;
}

.flex{
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
}

.with-align{
  text-align: center;
}
<div class="box flex">
  some long text here
</div>

<div class="box flex with-align">
  some long text here
</div>

1个回答

24

一个 flex 容器的 HTML 结构有三个级别:

  • 容器
  • 项(item)
  • 内容

每个级别都代表一个独立的元素。

justify-content 属性设置在 flex 容器上,用于控制 flex 项。它无法直接控制项的子元素(比如文本)。

当你在一个行方向容器上设置 justify-content: center 时,项会缩小到内容宽度(即缩小适应),并水平居中。由于内容位于项内部,所以内容也会随之移动。

一切看起来都很好,当内容窄于 flex 容器时

另一方面,当内容宽于 flex 容器时,flex 项就不能再居中了。实际上,该项无法对齐(startendcenter),因为没有可用空间 - 该项占据了容器的全部宽度。

在这种情况下,文本可以换行。但是,justify-content: center 不适用于文本。它从未适用于文本。文本始终受默认值的影响,即 text-align: start(在 LTR 中为 left,在 RTL 中为 right)。

因此,要直接居中文本,请将 text-align: center 添加到 flex 项(或 flex 容器中,由于继承所以并不重要)。

article {
  display: flex;
  align-items: center;
  justify-content: center;
}

.center {
  text-align: center;
}

/* demo styles only */
article {
  width: 100px;
  height: 100px;
  margin: 10px;  
  background-color: lightgreen;
}
<article>
  <p>some long text here</p>
</article>

<article>
  <p class="center">some long text here</p>
</article>


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