Stuck in the middle
When should I use margin-left:auto; margin-right:auto
to center and when should I use margin-left:50%; margin-right:50%
?
Maybe "auto" when I am centering something contained in another element & 50% when I am centering on the page?
Or I am I just hopelessly con开发者_JAVA百科fused?
margin-left:50% ; margin-right:50%;
would imply that the item you are centering has no width.
For a block level element like a div
, the best way to center it is:
div.centered { margin: 0 auto; }
The 0 before the auto refers to top and bottom so that can be set to whatever you like. The important part is the auto
which will cause the left and right margins to be automatically set and they will be equal regardless of how wide your element is.
Update: As pointed out by Phelios, a width should be specified for the div for this approach to work
Or I am I just hopelessly confused?
Maybe :)
margin-left: 50%; margin-right: 50%
is not generally useful: http://jsfiddle.net/VcDYr/- Where you might use
margin-left: 50%
is if you're centering like this: http://jsfiddle.net/VcDYr/1/ - To "center the page", you invariably want
margin-left: auto; margin-right: auto
. A shorter way to write this ismargin: 0 auto
: http://jsfiddle.net/VcDYr/2/
Consider that div
is a block-level element.
See: http://www.w3.org/TR/CSS21/box.html#margin-properties
auto - See the section on calculating widths and margins for behavior.
Which leads to: http://www.w3.org/TR/CSS21/visudet.html#Computing_widths_and_margins
Block-level, non-replaced elements in normal flow
'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block
If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.
To Center a div container you need to give it a width and a hight than you use
#div {
height: 700px;
width: 1000px;
margin: 0 auto;
}
精彩评论