Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
643 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...