html - 文本未以 justify-content : center 居中

标签 html css flexbox

我有一个带有 display: flex 的 div。其内容水平和垂直居中。

当 div 中的内容太长时,内容会换行。但是在这种情况下对齐被打破了。请参阅代码段。

如果我添加 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>

最佳答案

flex 容器的 HTML 结构分为三个层次:

  • 容器
  • 元素
  • 内容

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

在 flex 容器上设置的 justify-content 属性控制 flex 元素。它无法直接控制元素的子项(在本例中为文本)。

当您在行方向容器上设置 justify-content: center 时,元素会收缩到内容宽度(即收缩以适合)并水平居中。内容在元素内部,随行。

一切都很好地居中,当内容比 flex 容器窄时

另一方面,当内容比 flex 容器宽时, flex 元素不再居中。事实上,元素根本无法对齐(startendcenter),因为没有可用空间——元素正在消耗容器的全宽。

在这种情况下,文本可以换行。但是 justify-content: center 不适用于文本。它从来没有。文本始终遵循默认值 text-align: start (LTR 中的/RTL 中的)。

因此,要使文本直接居中,请将 text-align: center 添加到 flex 元素(或 flex 容器,由于 inheritance 并不重要)。

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>

关于html - 文本未以 justify-content : center 居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39678610/

相关文章:

css - float 菜单可变宽度

html - 等高列并将最后一项与底部对齐

javascript - 响应式设计 3 div 横跨布局,ul 堆叠在中心 div 下方

javascript - jQuery:计算有多少列表项将该值存储到变量中并将其作为文本传递到范围中

html - 在 Bootstrap 3 中将文本显示在与 block 级按钮相同的行上

javascript - 从 JavaScript 渲染 HTML 数组中的每个对象

html - 最小宽度在 IE 中不适用于卡住布局

javascript - 印地语在 Chrome 浏览器中呈现不正确

javascript - 如何为具有水平滚动的 flex 元素设置宽度?

css - Flexbox 嵌套列