Chowlett Chowlett - 1 year ago 84
CSS Question

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?

Answer Source

Off the top of my head:

  1. The element must display: block
  2. The element must not float
  3. The element must not have a fixed or absolute position

Off the top of other people's heads:

  1. The element must have a width that is not auto1

1 Technically, margin: 0 auto does work with an auto width, but the auto width takes precedence over the auto margins, and the auto margins are zeroed out as a result, making it seem as though they "don't work".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download