我有一个带有 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 元素不再居中。事实上,元素根本无法对齐(start
、end
、center
),因为没有可用空间——元素正在消耗容器的全宽。
在这种情况下,文本可以换行。但是 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/