learningtech
learningtech

Reputation: 33673

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.

Upvotes: 5

Views: 9750

Answers (4)

painotpi
painotpi

Reputation: 6996

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

Upvotes: 2

GibsonFX
GibsonFX

Reputation: 1060

You can use the following to vertically align anything

.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

Read more about it here: http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/

Upvotes: 1

ToddBFisher
ToddBFisher

Reputation: 11590

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/

Upvotes: 2

danielsan
danielsan

Reputation: 446

Purest way with css is to use the display attribute like so:

#foo { display: table; position: absolute; } 
#bar {
    display: table-cell;
    vertical-align: middle;
    height: 200px
}

then your html

<div id="foo">
    <div id="bar">
        Your text
    </div>
</div>

should be centered.. and #foo has it's position absolute that you don't want to get rid of..

Upvotes: 0

Related Questions