CSS - DIV content vertical alignment

I am trying to vertically focus some content using CSS. For my life, I can’t understand the reason. Can someone tell me why the word β€œtest” in the following HTML is always aligned in height 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> 

Many thanks for your help!

+7
html css
source share
6 answers

A quick way to align vertically, as in your case, is to match the height of the line 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> 
+4
source share

Since vertical-align is only a CSS replacement for the valign attribute in TD and therefore only works on display: table-cell elements (and no, the correct solution should not change the display mode of your DIV )

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

+4
source share
+3
source share

Try adding valign="middle" to the td tag, for example:

 <td valign="middle" style='height:200px; width:300px; background-color:silver;'> 
0
source share

Try setting the style = 'vertical-align: middle;' in the parent element. Right now you are really telling the inner div to align the text to the middle, however you are not telling it to stretch and occupy the entire page. Basically you get a div element that is smaller than the text.

You can use the Firebug plugin in Firefox to debug this type of CSS problem!

0
source share

try using line height: 100px

-2
source share

All Articles