”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 为什么 `justify-content: center` 不将 Flex 容器中的文本居中?

为什么 `justify-content: center` 不将 Flex 容器中的文本居中?

发布于2024-11-07
浏览:137

Why Doesn\'t `justify-content: center` Center Text in a Flex Container?

带有 justify-content 的非居中文本:center

在 Flex 容器中, justify-content 属性使 Flex 项目水平居中,但是它无法直接控制这些项目中的文本。当文本在项目内换行时,它会保留其默认的 text-align: start 值,从而导致文本不居中。

Flex 容器、Flex 项目和文本代表 HTML 结构中的三个不同级别。 justify-content 影响 Flex 项目,而不是其中包含的文本。

如果 Flex 项目填充其容器的宽度,则它无法居中,因此换行时文本未对齐。

To直接将文本居中,通过继承将 text-align: center 分配给 Flex 项目或容器。

示例

.box {
  width: 100px;
  height: 100px;
  background-color: lightgreen;
  margin: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.with-align p {
  text-align: center;
}

some long text here

some long text here

最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3