Vertical center align div using CSS

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

1. Using Table Property

Table property has the feature table-cell to align 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 the element in the vertical middle by using an 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: