为什么不margin-top:auto和margin-bottom:auto工作和他们的左右对等一样? [英] Why don't margin-top: auto and margin-bottom:auto work the same as their left and right counterparts?

查看:290
本文介绍了为什么不margin-top:auto和margin-bottom:auto工作和他们的左右对等一样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我设置一个div的CSS margin属性:

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

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



我得到一个在页面中水平居中的div,这样

但是,如果我将CSS更改为:

However, if I change the CSS to this:

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

my div不是垂直居中的。我不需要知道解决方法(许多解决方案可用),但我想知道此行为的原因。为什么margin-top和margin-bottom不以同样的方式工作?

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?

推荐答案

简短的答案是规范说的这样。

The short answer is the spec says so.


10.6.2内联替换元素,正常流中的块级替换元素,'inline-block'替换正常流中的元素和浮动替换元素



如果margin-top或margin-bottom为auto,则其使用值为0.

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

这篇关于为什么不margin-top:auto和margin-bottom:auto工作和他们的左右对等一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆