Why doesn’t “margin: auto” center an element vertically?
As you can see in the demo below,
margin: auto; centers the blue
div horizontally, but not vertically. Why not?
The question is not asking for workarounds.
It doesn’t center the element vertically because it is a block-level element in the normal flow. Thus, the following rule applies:
auto, their used value is 0.
- Inline replaced elements
- Block-level replaced elements in normal flow
inline-blockreplaced elements in normal flow
- Floating replaced elements
- Block-level non-replaced elements in normal flow when
With that being said, absolutely positioned, non-replaced elements that don’t have
bottom values of
auto are an exception to this rule. The following applies from point 10.6.4:
If none of the three
autoand if both
auto, solve the equation under the extra constraint that the two margins get equal values.
See the example below demonstrating how an absolutely positioned element is vertically centered using
margin: auto. It works because none of the three properties
bottom have a value of
In addition, it’s probably worth pointing out the following rule as well:
If one of
auto, solve the equation for that value. If the values are over-constrained, ignore the value for
bottomand solve for that value.
This means that if the absolutely positioned element has a
margin-top value of
auto and a
margin-bottom value of
margin: auto auto 0), the element would be absolutely positioned at the bottom relative to the parent like in the example below: