我和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>
发布于 2016-09-25 02:44:29
flex容器的HTML结构有三个级别:
每个级别代表一个独立的元素。
在flex容器上设置的justify-content属性控制flex项。它不能直接控制项的子项(在本例中是文本)。
当您在行方向容器上设置justify-content: center时,项目将收缩到内容宽度(即,收缩到适合的宽度)并水平居中。内容,在项目中,是顺其自然的。
当内容比flex容器更窄时,一切都会很好地居中。
另一方面,当内容比flex容器更宽时,flex项不能再居中。事实上,该项目根本不能对齐(start、end、center),因为没有可用的空间-该项目正在消耗容器的整个宽度。
在这种情况下,文本可以换行。但是justify-content: center不适用于文本。它从来都没有。文本始终遵循默认 ( LTR中的left/RTL中的right )。
因此,要将文本直接居中,可以将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>
https://stackoverflow.com/questions/39678610
复制相似问题