[css] Center text in div?

I have a div 30px high and 500px wide. This div can contain two lines of text one under the other, and is styled (padded) accordingly. But sometimes it only contains one line, and I want it to be centered. Is this possible?

This question is related to css padding spacing

The answer is


To center horizontally, use text-align:center.

To center vertically, one can only use vertical-align:middle if there is another element in the same row that it is being aligned to.
See it working here.

We use an empty span with a height of 100%, and then put the content in the next element with a vertical-align:middle.

There are other techniques such as using table-cell or putting the content in an absolutely positioned element with top, bottom, left, and right all set to zero, but they all suffer from cross browser compatibility issues.


Adding line height helps too.

text-align: center;
line-height: 18px; /* for example. */

If you have text inside a <div>:

text-align: center;
vertical-align: middle;
display: table-cell;

HTML

<div class="outside">
  <div class="inside">
      <p>Centered Text</p>
  </div>
</div>

CSS

.outside { 
  position: absolute; 
  display: table; 
}

.inside {
  display: table-cell; 
  vertical-align: middle; 
  text-align: center; 
}

I may be missing something here, but have you tried:

text-align:center; 

??


div {
    height: 256px;
    width: 256px;
    display: table-cell;
    text-align: center;
    line-height: 256px;
}

The trick is to set the line-height equal to the height of the div.


display: block;
text-align: center;

Will this work for you?

div { text-align: center; }

Add to the selector containing the text

margin:auto;

I've looked around and the

display: table-cell;
vertical-align: middle;

seems to be the most popular solution


I believe you want the text to be vertically centered inside your div, not (only) horizontally. The only reliable way I know of doing this is using:

display: table-cell;
vertical-align: middle;

on your div, and it works with any number of lines. You can see a test here: http://jsfiddle.net/qMtZV/1/

Be sure to check browser support of this property, as it is not supported — for example — in IE7 or earlier.

UPDATE 02/10/2016

Five years later this technique is still valid, but I believe there are better and more solid solutions to this problem. Since Flexbox support is good nowadays, you might want to do something along these lines: http://codepen.io/michelegera/pen/gPZpqE.


For the parent div,use following CSS:

style="display: flex;align-items: center;"