Pedro Pedro - 6 months ago 8
CSS Question

Vertical center text which overflows at bottom only

I would like to center text in a container

div
, such that when it overflows it only overflows on the bottom.

A single line of text would be centered:

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


Two or three lines of text (as many as needed to fill the container) would also be centered.

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


But when there is too much text for the container, it would start overflowing at the bottom (eventually being hidden by CSS).

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


How can this be achieved with CSS?




NOT a duplicate of:


  • stackoverflow.com/q/15680785/3597276 (in my case, I need the text to be centered vertically when it fits the container)


Answer

Would this work for you?

.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>