Centering a <div>

Typically, we specify a width and auto margins on the left and right to center a div.  However, there is another way we can center a div.

#container {
    width: 800px;
    margin: 0 auto 0 auto;
}

There is another way.......

This <div> is centered by using a margin on both the left and right. I added a top and bottom margin as well.  I left the width property blank.  Why does this work? 

Well..... a div is a block level element. 

As such, if we leave the width of a div blank, it will simply expand across the entire width of the page or the width of the div it is nested inside of.  Adding left and right margins creates space between the left and right edge of the div and the page or div it is nested inside of.

  

 

The Style Will Look like This:

#container {
    margin: 10px 25px;
    background-color: #000000; 
    color: #ffffff; 
    padding: 10px;
}

A Width is not necessary because a static <div> is a block level element, which means the <div> will automatically extend all the way across the initial containing block (the body or another div).

Therefore, adding equal left and right margins to a static <div> will cause the <div> to be centered horizontally.

(this cannot be done with a layer, which is absolutely positioned (ap).  Well, if you use negative margins on the left and right, then you could center an ap div.)  But in general, an absolute div (ie. layer) requires a width.  Once you have a width specified, then the margins will not be enough to center the div (unless you toy with negative margins using %.)  You could try to apply auto margins Left and right for the layer, but this only works with a static div. 

But what if I want to center the container that has a % for a width?  (ie. a fluid layout)

No problem.  Simply provide auto margins for the left and right, and the div will center. 

#container {
width:95%;
margin: 0 auto 0 auto;
}

You can specify the width a div using pixels, ems, or % and still center the div.  The div must be a static div, with a width, and auto margins on the left and right.

Or- do not specify a width and just specify EQUAL Right and Left Margins....and the static div will center.  This is because the width of the div will be determined by the amount left over after the margins are applied.  It also means the container will stretch or shrink based upon the size of a viewers computer screen.