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?
Off the top of my head:
- The element must be block-level, e.g.
display: block
ordisplay: table
- The element must not float
- The element must not have a fixed or absolute position1
Off the top of other people's heads:
- The element must have a
width
that is notauto
2
Note that all of these conditions must be true of the element being centered for it to work.
1There is one exception to this: if your fixed or absolutely positioned element has left: 0; right: 0
, it will center with auto margins.
2Technically, 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".
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:
- (
display: block
ANDwidth
not auto) ORdisplay: table
float: none
-
position: relative
ORposition: static
OR
- parent element with
display: flex
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.
Off the top of my head, if the element is not a block element - make it so.
and then give it a width.