There are times when you need to create some html elements and you want to position them at the center of the screen. For example fading messages, warnings, etc..

Here is the simple CSS rule to do just that:

<div id="my-div">
   Will be right at the center of the screen
</div>

And your css:

    #my-div {
        position: fixed;
        width: 20%; /* Set your desired with */
        z-index: 2; /* Make sure its above other items. */
        top: 50%;
        left: 50%;
        margin-top: -10%; /* Changes with height. */
        margin-left: -10%; /* Your width divided by 2. */

        /* You will not need the below, its only for styling   purposes. */
        padding: 10px;
        border: 2px solid #555555;
        background-color: #ccc;
        border-radius: 5px;
        text-align: center;
    }

There are couple of things going on here. The fixed position allows us to separate from the parent of the div element and allows us to hover over the screen. By setting ‘top’ and ‘left’ rules to 50%, we position the top left corner of the div element at the center of the screen. Finally by using the half of the width of the div element we negative offset the left margin, we center the div’s center at the center of the screen.

You can center any html element using the above css.

Click here for the DEMO