tags:

views:

154

answers:

5

Hello,

I am trying to vertically center some content via CSS. For the life of me, I cannot figure out the cause. Can someone tell me why the word "test" in the following HTML is always top-aligned no matter what I do?

<html>
    <head>
     <title>test</title>
    </head>

    <body>
     <table border='0' cellpadding='0' cellspacing='0'>
      <tr><td style='height:200px; width:300px; background-color:silver;'>
       <div style='height:100%; width:100%; background-color:gray; text-align:center;'>
        <div style='vertical-align:middle;'>test</div>
       </div>
      </td></tr>
     </table>
    </body>
</html>

Thank you very much for your help!

A: 

Try adding valign="middle" to your td tag, like:

<td valign="middle" style='height:200px; width:300px; background-color:silver;'>
inkedmn
Probably this works in most browsers, but it is not standards-compliant. On the other hand, the use of tables isn't nice either.
Martijn
A: 

Try setting style='vertical-align:middle;' in the parent element. Right now you are indeed telling the inner div to align the text to the middle, however you're not telling it to stretch and occupy the whole page. Basically you're ending up with a div element that's as small as the text.

You can use Firebug plugin in Firefox to debug this kind of CSS issue!

ruibm
A: 

try using line-height:100px

Saif Bechan
+1  A: 

A quick way to vertical align, like in your case, is to match the line-height with the height.

<html>
    <head>
        <title>test</title>
    </head>
    <body>
        <table border='0' cellpadding='0' cellspacing='0'>
                <tr><td style='height:200px; line-height: 200px; width:300px; background-color:silver;'>
                        <div>
                            <div style="text-align: center">test</div>
                        </div>
                </td></tr>
        </table>
    </body>
</html>

F.Aquino
+1  A: 

Because vertical-align is only a CSS substitute to the valign attribute in TD, and therefore only works on display: table-cell elements (and no, the proper solution is not to change the displaymode of your DIV)

If you can set a fixed height to the div, you should be able to align it vertically with margin: auto 0

David Hedlund