21

If I set the CSS margin properties of a div like so:

div { margin-left: auto; margin-right: auto; }

I get a div which is centered horizontally in the page, like so.

However, if I change the CSS to this:

div { margin-top: auto; margin-bottom: auto; }

my div is not vertically centered. I don't need to know a workaround (plenty of solutions are available) but I would like to know the reason for this behaviour. Why don't margin-top and margin-bottom work in the same way? What am I missing?

1
  • For anyone reading this in 2017 or later, the answer now seems to be: they do, but only if you're using flexbox. If your parent element has display: flex; then margin: auto; on a child will center it horizontally and vertically.
    – Andy F
    Aug 20, 2017 at 21:39

2 Answers 2

22

The short answer is the spec says so.

10.6.2 Inline replaced elements, block-level replaced elements in normal flow, 'inline-block' replaced elements in normal flow and floating replaced elements

If 'margin-top', or 'margin-bottom' are 'auto', their used value is 0.

http://www.w3.org/TR/CSS2/visudet.html#Computing_heights_and_margins

2
  • 1
    does padding act the same regarding top/bottom ?
    – sam
    Jun 3, 2012 at 16:32
  • 2
    @sam: The used value is always zero for padding: auto on any side.
    – BoltClock
    Sep 12, 2012 at 11:16
1

Assuming we are talking about auto margins within a Flexbox..

The reason that margin-left and margin-right set to auto will center an item is because the width by default is 100% of the available container for a block element.

The height on the other hand attempts to fill as little as the space as possible, so margin-top and margin-bottom as auto will default to 0. BUT, if your element is within an element with a fixed height, then margin-top and margin-bottom will be able to calculate the center based on that height.

Ex. http://jsfiddle.net/jwz76e3g/24/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.