div position center of screen

An age old question with a simple answer:
How to position a div in the center of (any size) browser window?

Once you have created your html page, create the div you wish to have in the center of the window and give it an id:

<div id="container">
  My center div...

From here on we have two options: either CSS or Javascript (using JQuery) :

The CSS solution:

We are going to give it a background color for display purposes, and a size of 100px by 100px.

#container {
  width: 100px;
  height: 100px;
  background-color: #567;

And lastly the trick:
We position the div absolute to the browser window, 50% from the top and 50% from the left.
Example of div positioned 50% from top and 50% from the left
But now the top left corner is in the center of the browser window, so to fix this we apply a negative margin of half the div size (50px in this case) to both left and top, leaving the center of the div in the center of the browser window.
Example of div with negative margin of half its width and half its height

Here is the final css:

#container {
  width: 100px;
  height: 100px;
  background-color: #567;
  left: 50%;
  top: 50%;
  margin-left: -50px;
  margin-top: -50px;

The javascript (using JQuery) solution:

With JQuery we have an advantage in that we can use calculations to determine the offset from the top left corner of the browser window.
We use the $(window).resize() function so that if they resize their screen the event will trigger and the div will auto position again.
We use outerWidth() and outerHeight() to get the width and height of the div including its border and padding.
Here is the final script:

    left: ($(window).width() - $('#container').outerWidth())/2,
    top: ($(window).height() - $('#container').outerHeight())/2

// To initially run the function:

Pros and cons of the two methods

With css we need to know the size of the div beforehand to position it, but a browser with javascript disabled can still view it correctly.
With javascript we don’t have to know or calculate the size of the div beforehand, but then the implementation is dependant on having javascript enabled.