Vertical center align div using CSS

When you are designing a page you need to align some elements in center or middle vertical. Then you have to use one from following methods.

1. Using Table Property

Table property have the feature table-cell to aligh the element in middle by css.

display: table-cell;
vertical-align: middle;

For example:

<html>
    <head>
        <style>
            .middle{
                 display: table-cell;
                 vertical-align: middle;
                 height: 200px;
            }
            .object{
                background: blue;
                color: white;
            }
        </style>
    </head>
    <body>
        <div class="middle">
            <div class="object">Hello World</div>
        </div>
    </body>
</html>

2. Using Absolute Property

You can also align element in vertical middle by using absolute feature of css. It requires element height should be fixed 

margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
height: 30px;

For example:

<html>
    <head>
        <style>
            .middle{
                 position: relative;
                 height: 200px;
            }
            .object{
                margin: auto;
                position: absolute;
                top: 0;
                left: 0;
                bottom: 0;
                right: 0;
                background: blue;
                width: 100px;
                height: 30px;
            }
        </style>
    </head>
    <body>
        <div class="middle">
            <div class="object">Hello World</div>
        </div>
    </body>
</html>

Output:

 


Keywords: