【发布时间】: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