【问题标题】:Why don't margin-top: auto and margin-bottom:auto work the same as their left and right counterparts?为什么 margin-top: auto 和 margin-bottom:auto 不与左右对应物一样工作?
【发布时间】:2011-07-21 11:25:59
【问题描述】:

如果我像这样设置 div 的 CSS 边距属性:

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

我得到一个在页面中水平居中的 div,like so

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

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

我的 div 不是垂直居中的。我不需要知道解决方法(plenty of solutionsare available),但我想知道这种行为的原因。为什么 margin-top 和 margin-bottom 的工作方式不同?我错过了什么?

【问题讨论】:

  • 对于 2017 年或以后阅读本文的任何人,现在的答案似乎是:他们会这样做,但前提是您使用的是 flexbox。如果您的父元素有display: flex;,那么子元素上的margin: auto; 会将其水平居中

标签: css


【解决方案1】:

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

10.6.2 内联替换元素、正常流程中的块级替换元素、正常流程中的“inline-block”替换元素和浮动替换元素

如果 'margin-top' 或 'margin-bottom' 为 'auto',则它们的使用值为 0。

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

【讨论】:

  • 填充对于顶部/底部的行为是否相同?
  • @sam:padding: auto 在任何一侧的使用值始终为零。
【解决方案2】:

假设我们讨论的是 Flexbox 中的自动边距..

margin-leftmargin-right 设置为 auto 的原因是因为默认情况下宽度是块元素可用容器的 100%。

另一方面,高度试图尽可能少地填充空间,因此margin-topmargin-bottom as auto 将默认为0。但是,如果您的元素位于具有固定高度的元素内,然后margin-topmargin-bottom 将能够根据该高度计算中心。

例如。 http://jsfiddle.net/jwz76e3g/24/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    相关资源
    最近更新 更多