Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS - Vertically Align DIV content

Tags:

html

css

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!

like image 642
user208662 Avatar asked Dec 10 '09 14:12

user208662


People also ask

How do I vertically align a div content?

To center a div vertically on a page, you can use the CSS position property, top property, and transform property. Start by setting the position of the div to absolute so that it's taken out of the normal document flow. Then set the top property to 50%.

How do I vertically align text in a div using CSS?

The CSS just sizes the div, vertically center aligns the span by setting the div's line-height equal to its height, and makes the span an inline-block with vertical-align: middle. Then it sets the line-height back to normal for the span, so its contents will flow naturally inside the block.

How do you vertically align items in CSS?

The vertical-align property in CSS controls how elements set next to each other on a line are lined up. In order for this to work, the elements need to be set along a baseline. As in, inline (e.g. <span> , <img> ) or inline-block (e.g. as set by the display property) elements.


1 Answers

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>
like image 90
Francisco Aquino Avatar answered Sep 28 '22 09:09

Francisco Aquino