我正在尝试使用水平容器,填充可变大小的文本。 如果文本很短,则容器应具有最小高度并垂直居中。 如果文本较长,容器应增加其高度,保持垂直和底部边距。
我准备了jsfiddle
这个小提琴的灵感来自于this answer,也在this answer和this one中尝试了display: table
答案 0 :(得分:6)
您可以使用flexbox并将内容置于justify-content
div.row {
border: 1px dotted black;
min-height:65px;
display:flex;
flex-direction:column;
justify-content:center;
}

<div class="row">
<div class="content">
This is a case where we have a small text;
</div>
</div>
<div class="row">
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sagittis felis ultricies fermentum elementum. Duis sollicitudin, ligula in posuere sagittis, nibh ex imperdiet ante, quis efficitur est nisl quis nulla. Donec pharetra feugiat arcu sed hendrerit. Integer aliquet porta erat, quis aliquet eros. Sed in pulvinar felis, eget lobortis dui. Vestibulum vitae imperdiet orci, in varius magna. Praesent venenatis, eros quis tristique accumsan, justo tellus tempus metus, vitae pellentesque nisl risus eu diam. Suspendisse lobortis ex et fringilla mattis.
</div>
</div>
&#13;
答案 1 :(得分:1)
Flexbox是最明显的选择,但如果浏览器支持成为问题,CSS Table就像Flexbox一样简单。
已更新(感谢Gaby aka G. Petrioli)
由于某种原因,Firefox似乎不再尊重min-height
上的table
。幸运的是,table
元素会随着内容的增长而增长,因此只需将min-height
更改为height
即可。
div.row {
display: table;
width: 100%;
border: 1px dotted black;
height: 65px;
}
div.content {
display: table-cell;
vertical-align: middle;
}
&#13;
<div class="row">
<div class="content">
This is a case where we have a small text;
</div>
</div>
<div class="row">
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sagittis felis ultricies fermentum elementum. Duis sollicitudin, ligula in posuere sagittis, nibh ex imperdiet ante, quis efficitur est nisl quis nulla. Donec pharetra feugiat arcu sed hendrerit. Integer aliquet porta erat, quis aliquet eros. Sed in pulvinar felis, eget lobortis dui. Vestibulum vitae imperdiet orci, in varius magna. Praesent venenatis, eros quis tristique accumsan, justo tellus tempus metus, vitae pellentesque nisl risus eu diam. Suspendisse lobortis ex et fringilla mattis.
</div>
</div>
&#13;