[css] What, exactly, is needed for "margin: 0 auto;" to work?

I know that setting margin: 0 auto; on an element is used to centre it (left-right). However, I know that the element and its parent must meet certain criteria for the auto margin to work, and I can never seem to get the magic right.

So my question is simple: what CSS properties have to be set on an element and its parent in order for margin: 0 auto; to left-right centre the child?

This question is related to css

The answer is


For anybody just now hitting this question, and not being able to fix margin: 0 auto, here's something I discovered you may find useful: a table element with no specified width must have display: table and not display: block in order for margin: auto to do work. This may be obvious to some, as the combination of display: block and the default width value will give a table which expands to fill its container, but if you want the table to take it's "natural" width and be centered, you need display: table


Off the top of my cat's head, make sure the div you're trying to center is not set to width: 100%.

If it is, then the rules set on the child divs are what will matter.


It will also work with display:table - a useful display property in this case because it doesn't require a width to be set. (I know this post is 5 years old, but it's still relevant to passers-by ;)


Off the top of my head, if the element is not a block element - make it so.

and then give it a width.


It's perhaps interesting that you do not have to specify width for a <button> element to make it work - just make sure it has display:block : http://jsfiddle.net/muhuyttr/


Here is my Suggestion:

First: 
      1. Add display: block or table
      2. Add position: relative
      3. Add width:(percentage also works fine)
Second: 
      if above trick not works then you have to add float:none;

Off the top of my head, it needs a width. You need to specify the width of the container you are centering (not the parent width).


Complete rule for CSS:

  1. (display: block AND width not auto) OR display: table
  2. float: none
  3. position: relative

Please go to this quick example I've created jsFiddle. Hopefull it's easy to understand. You can use a wrapper div with the width of the site to center align. The reason you must put width is that so browser knows you are not going for a liquid layout.