Off the top of my head:
- The element must be block-level, e.g.
display: block
or display: 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 not auto
2
Note that all of these conditions must be true of the element being centered for it to work.
1 There is one exception to this: if your fixed or absolutely positioned element has left: 0; right: 0
, it will center with auto margins.
2 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".
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…