Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't margin-top: auto and margin-bottom:auto work the same as their left and right counterparts?

Tags:

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?

like image 336
Andy F Avatar asked Jul 21 '11 11:07

Andy F


People also ask

Why is my margin auto not working?

margin: auto; , it will not work. This is because by default the block-level elements such as a div, p, list, etc take up the full width of its parent element, and no space is left to adjust the element horizontally. So, the very first thing you need to check is whether you have set the width of the element or not.

Why margin-top is not working in a tag?

This issue is known as Margin Collapse and happens sometimes between top and bottom margins on block elements. That's why the margin doesn't work on the p tag. To make it work here an option is to use padding-top on the p tag. And on the a tag the margin doesn't work because it's an inline element.

How do you set the top left and bottom right of a margin?

Two Values The syntax for the CSS margin property (with 2 values) is: margin: top_bottom left_right; When two values are provided, the first value will apply to the top and bottom of the element. The second value will apply to the left and right sides of the element.

What will happen if the margin is set to auto?

The auto Value You can set the margin property to auto to horizontally center the element within its container. The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.


1 Answers

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

like image 126
Jason Gennaro Avatar answered Oct 20 '22 01:10

Jason Gennaro