垂直中心文字仅在底部溢出

时间:2016-05-21 18:07:53

标签: css css3 flexbox

我想将文本放在容器div中居中,这样当它溢出时它只会溢出底部。

单行文本将居中:

------------------------
|                      |
|A line of text        |
|                      |
------------------------

两行或三行文本(填充容器所需的数量)也将居中。

------------------------
|A line of text        |
|A line of text        |
|A line of text        |
------------------------

但是当容器的文本太多时,它会在底部开始溢出(最终被CSS隐藏)。

------------------------
|A line of text        |
|A line of text        |
|A line of text        |
------------------------
A line of overflown text
A line of overflown text

如何通过CSS实现这一目标?

不是重复:

  • stackoverflow.com/q/15680785/3597276(在我的情况下,我需要文本在适合容器时垂直居中)

1 个答案:

答案 0 :(得分:2)

这对你有用吗?



.parent {
  margin: 10px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
  width: 200px;
  border: 1px solid;
}
.child {
  max-height: 100%;
  /* overflow: hidden; */
}

<div class="parent">
  <div class="child">
    Line of text
  </div>  
</div>
<div class="parent">
  <div class="child">
    Line of text<br>
    Line of text<br>
  </div>  
</div>
<div class="parent">
  <div class="child">
    Line of text<br>
    Line of text<br>
    Line of text<br>
    Line of text<br>
    Line of text<br>
    Line of text<br>
  </div>  
</div>
&#13;
&#13;
&#13;