Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align text to the center of a div

Tags:

html

css

layout

I have a div thats about 200px x 40px. Sometimes this block will contain a single line of text and other times it will contain two lines. In the case that it contains 2 lines of text, I have adjusted the line height so that it looks balanced inside of the div. However, in the case that there is a single line of text, the text lines up with the top of the div, leaving the bottom empty.

Instead, I want the single line of text to appear vertically centered inside of the div. What is the best way to set this up? Should I place the text inside of a secondary element like <p> and then attempt apply vertical-align: middle? It seems like there should be a simpler, more streamlined way to accomplish this. Any Ideas?

like image 726
Thomas Avatar asked Dec 22 '22 01:12

Thomas


2 Answers

I'm not sure if it works in any browser (works on Firefox, Chrome, IE8) (doesn't work on IE7-)

<div style="display: table-row; height: 180px; width: 500px;">
    <div style="display: table-cell; vertical-align: middle; width: 500px; text-align: center;">Text</div>
</div>

The only solution I know that definitely works in any browser is to create a table and apply the vertical align on a cell.

like image 199
BrunoLM Avatar answered Jan 15 '23 14:01

BrunoLM


Although it seems to be a simple problem there is no straightforward solution for it in CSS2 AFAK. Theme Forrest features a good overview of different approaches to this problem.

like image 42
cmaderthaner Avatar answered Jan 15 '23 14:01

cmaderthaner