Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically center text in a 100% height div?

I am working with a div that is 100% of the parent divs height.

The div only contains a single line of text.

The div cannot have a fixed height.

So my question is.

How do I vertically center the line of text?

I have tried using:

display: table-cell;   line-height:200%; 

If it is important the div is absolutely positioned.


Current CSS
.requests {     position: absolute;     right: 0;     height: 100%;     width: 50px;     padding: 0 10px;     background-color: #69A4B5;     display: table-cell;     vertical-align: middle;     border-bottom-right-radius: 5px; } 
like image 277
Hailwood Avatar asked Jan 20 '11 23:01

Hailwood


People also ask

How do I center text vertically in a div?

To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.

How do I center text in a div height?

Answer: Use the CSS line-height property Suppose you have a div element with the height of 50px and you have placed some link inside the div that you want to align vertically center. The simplest way to do it is — just apply the line-height property with value equal to the height of div which is 50px .

How do I center text vertically in line-height?

Use line-height for vertical centering with a fixed height To vertically center a single line of text or an icon within its container, we can use the line-height property. This property controls the height of a line in a run of text and adds an equal amount of space above and below the line-box of inline elements.


1 Answers

The best and easiest way to do it (currently in 2015 2020) is using flexbox:

.parent-selector {     display: flex;     align-items: center; } 

And that's it :D

Check-out this working example:

div {      border: 1px solid red;      height: 150px;      width: 350px;      justify-content: center;        /* Actual code */      display: flex;      align-items: center;  }
<div>      <p>Hola</p>  </div>

Old answer: You can use vertical-align: middle if you specify also display: table-cell;

.div {     display: table-cell;     vertical-align: middle; } 

Working example:

div {    border: 1px solid red;    height: 150px;    width: 350px;    text-align: center;        /* Actual code */    display: table-cell;    vertical-align: middle;  }
<div>      <p>Hola</p>  </div>

If it does not work you can try setting its parent as display: table;:

.parent-selector {     display: table; } 

Edit: You have this method plus all the methods covered on this question in this other question: How do I vertically center text with CSS?

like image 112
elboletaire Avatar answered Sep 22 '22 17:09

elboletaire