Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 688
Rifki Avatar asked May 19 '11 07:05

Rifki


People also ask

How do I center text inside a div?

You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.

How do you center align text?

Select the text that you want to center. in the Page Setup group, and then click the Layout tab. In the Vertical alignment box, click Center. In the Apply to box, click Selected text, and then click OK.

How do I vertically align text in a div using CSS?

The CSS just sizes the div, vertically center aligns the span by setting the div's line-height equal to its height, and makes 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.


2 Answers

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.

like image 127
SamGoody Avatar answered Oct 05 '22 13:10

SamGoody


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.

like image 26
michelegera Avatar answered Oct 05 '22 13:10

michelegera