Irakli Lekishvili Irakli Lekishvili - 5 months ago 7
HTML Question

How to vertically center text with CSS?

I have a div tag which contains text, and I want to align the contents of this div vertically center.

Here is my div style:



#box
{
height: 90px;
width: 270px;
background: #000;
font-size: 48px;
font-style: oblique;
color: #FFF;
text-align: center;
margin-top: 20px;
margin-left: 5px;
}

<div Id="box">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>





What is the best way to do this?

Answer

You can try this basic approach:

#box {
  height: 90px;
  line-height: 90px;
}

Demo

Only works for a single line of text though, because we set the line's height to the same height as the containing box element.


A more versatile approach

And here is another way to align text vertically, this solution will work for a single line and multiple lines of text, but still requires a fixed height container:

<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</div>

The CSS just sizes the <div>, then vertically center aligns the <span> by setting the <div>'s line-height equal to its height, and making the <span> an inline-block with vertical-align: middle. Then it sets the line-height back to normal for the <span> so its contents will flow naturally inside the block.

div {
  width: 250px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

span {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;      
}

Demo


Simulating table display

And here is another option, which may not work on older browsers that don't support display: table and display: table-cell (basically that means Internet Explorer 7). The HTML is the same as the second example:

<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</div>

Using CSS we 'simulate' table display behavior, since tables support vertical alignment:

div {
  display: table;
  width: 250px;
  height: 100px;
  text-align: center;
}

span {
  display: table-cell;
  vertical-align: middle;
}

Demo


Using absolute positioning

This technique uses an absolutely positioned element setting top, bottom, left and right to 0. It is described in more detail in an article on Smashing Magazine.

Comments