我有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>
&#13;
答案 0 :(得分:12)
Flex容器的HTML结构有三个级别:
每个级别代表一个独立的独立元素。
在Flex容器上设置的justify-content
属性控制弹性项。它无法直接控制项目的子项(在本例中为文本)。
当您在行方向容器上设置justify-content: center
时,项目缩小到内容宽度(即缩小到适合)并且水平居中。内容在项目内部,随身携带。
当内容比flex容器更窄时,一切都很好地居中,。
另一方面,当内容比flex容器更宽时,flex项不能再居中。实际上,该项目根本无法对齐(start
,end
,center
),因为没有可用空间 - 该项目占用了容器的整个宽度。
在这种情况下,文本可以换行。但justify-content: center
并不适用于该文字。它从来没有。该文字始终受默认text-align: start
(RTL中LTR / left
right
}的约束。
因此,要直接将文本居中,请将text-align: center
添加到弹性项目(或弹性容器,由于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;
}
&#13;
<article>
<p>some long text here</p>
</article>
<article>
<p class="center">some long text here</p>
</article>
&#13;