0

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 confused?

Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551
  • 1
    you can never use margin-left and margin-right simultaneously for better results. Better Use Div in the top and put text-align: center; – Max Jun 02 '11 at 09:18
  • 1
    Possible duplicate of http://stackoverflow.com/questions/4955122/what-exactly-is-needed-for-margin-0-auto-to-work ? – Chowlett Jun 02 '11 at 09:19

3 Answers3

5

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

Nikola K.
  • 7,093
  • 13
  • 31
  • 39
Brendan Bullen
  • 11,607
  • 1
  • 31
  • 40
  • 4
    given that you must specify width – Sufendy Jun 02 '11 at 09:21
  • "margin-left:50% ; margin-right:50%; would imply that the item you are centering has no width" – Mawg says reinstate Monica Jun 02 '11 at 14:21
  • "margin-left:50% ; margin-right:50%; would imply that the item you are centering has no width" - does it? 2 possibilities: 1) that is true and the browser is forgiving, since submit buttons and text centered that way _are_ shown 2) the browser _first_ calculates the size of the item (submit button, text, etc) then sets the margins to 50% of whatever is left. In either case, it seems to work, even if it is "wrong" – Mawg says reinstate Monica Jun 03 '11 at 02:05
3

Or I am I just hopelessly confused?

Maybe :)

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.

thirtydot
  • 224,678
  • 48
  • 389
  • 349
1

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;
}
Nikola K.
  • 7,093
  • 13
  • 31
  • 39
Rafael Marques
  • 797
  • 1
  • 8
  • 18