文本以最小高度为中心并调整容器的高度

时间:2017-06-11 19:47:39

标签: html css css3 flexbox css-tables

我正在尝试使用水平容器,填充可变大小的文本。 如果文本很短,则容器应具有最小高度并垂直居中。 如果文本较长,容器应增加其高度,保持垂直和底部边距。

我准备了jsfiddle 这个小提琴的灵感来自于this answer,也在this answerthis one中尝试了display: table

2 个答案:

答案 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;
&#13;
&#13;

答案 1 :(得分:1)

Flexbox是最明显的选择,但如果浏览器支持成为问题,CSS Table就像Flexbox一样简单。

已更新(感谢Gaby aka G. Petrioli

由于某种原因,Firefox似乎不再尊重min-height上的table。幸运的是,table元素会随着内容的增长而增长,因此只需将min-height更改为height即可。

&#13;
&#13;
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;
&#13;
&#13;