Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use CSS to vertically align text?

I have a blue box on a page that is 100 px from the top and left. Then I want text in the blue box to vertically align. Why won't my code below vertically align the text?

<!DOCTYPE html>
<html>
        <body>
                <div style="height:200px; background:blue; display:table-cell; vertical-align:middle; color:white;position:absolute; top:100px; left:100px;">
                        this is text;
                </div>
        </body> 
</html>

How do I get the text to vertically align?

Notes - If I remove position absolute, then the text vertically aligns. But this is not acceptable, because I need absolute positioniong for some other things.

like image 366
John Avatar asked Dec 14 '12 03:12

John


2 Answers

Contain it in a separate div like this:

CSS

#Div0 {
    position:absolute; 
    top:100px; 
    left:100px;
}

#Div1 {
    height:200px; 
    background:blue; 
    display:table-cell; 
    vertical-align:middle; 
    color:white;
}

HTML

<div id="Div0">
    <div id="Div1">
        this is text
    </div>
</div>​​​​​​​​​​​​​​​​​​​

Solution Example: http://jsfiddle.net/rgDfg/

like image 169
ToddBFisher Avatar answered Sep 22 '22 16:09

ToddBFisher


It'll work if you remove the position: absolute;

So your CSS will look like this,

div{
    height:200px;        
    background:blue; 
    display:table-cell;
    vertical-align: middle;
    color: white;
}

Check the fiddle link

like image 39
painotpi Avatar answered Sep 22 '22 16:09

painotpi