Horizontally and Vertically Center a DIV with CSS…

An extremely simple solution to a surprisingly elusive problem. To perfectly center a DIV on an HTML page simply use the following approach.

The HTML…

<body>
    <div class="centered">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
</body>

 

The CSS that does the centering…

.centered {
   position: fixed;
   top: 50%;
   left: 50%;
   height: 100px;
   margin-top: -50px;
   width: 200px;
   margin-left: -100px;
}

For this to work beautifully make sure that margin-top is exactly half of the height and same goes for margin-left which should be exactly half of the width. Also note that CSS does not support decimals.

This images helped me visualise what was going on…

Horizontally and Vertically Center a DIV with CSS…

10 thoughts on “Horizontally and Vertically Center a DIV with CSS…

  1. God Bless you! I’ve been searching all weekend long to find this simple yet oh-so-hard to achieve task! You saved me! Thanks so much!

  2. I must say the best solution I’ve found all afternoon. Simple, does not leave important information out and does not make assumptions. Great cheers.

  3. Javi Esteban says:

    Hi Ben,

    What happens if the height and width of the div are “%”. Do you know how can i fix a div in the center of the site?

    Thanks!!

    1. If your using percentages you can’t use this method. However you may be able to set the ‘box’ CSS to

      margin: 0 auto;

      and have a full screen width and full screen height DIV (acting like a second BODY tag) with its CSS set to

      position: absolute; top: 0; left: 0;

      .

  4. Ming Yen C. says:

    This method works Great!! but it doesn’t work with firefox. any ideas how to fix this?

Leave a Reply

Your email address will not be published. Required fields are marked *