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.
There is another way.......
A div can be centered by using a margin on both the left and right. Then add a top and bottom margin as well. Why does this work?
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 (containing block) 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.
1. Place a <div> on your web page.
2. Click New Style, Make
the Selector #container
3. Set the margins to 10px for top and
bottom, 25px for left and right.
Also set the padding to 10px for all
4 sides.
4. Background color: #000000 (black)
5. Font
Color: #FFFFFF (white)
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.
You can specify the width for 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.