Css 中的垂直对齐是一个既有趣又痛苦的话题。这个stackoverflow queston是我见过的关于为什么垂直对齐会如此痛苦的最简洁的解释
至于你的第一个问题,你不能使用边距垂直对齐的原因在下面的引用中解释了。
...文档流和元素高度计算算法的性质使得不可能使用边距在其父元素内垂直居中。每当更改垂直边距值时,都会触发父元素高度重新计算(重排),这反过来又会触发原始元素的重新居中……使其成为无限循环。
至于您的第二个问题,margin auto 通过计算子容器相对于其父容器宽度的宽度来实现水平居中。然后它通过简单的数学运算在子容器的左右两侧添加均匀的边距,强制水平居中。
至于第二个问题 B 部分,
margin: auto
与以下相同:
margin-top: auto;
margin-bottom: auto;
margin-right: auto;
margin-left: auto;
其中 asmargin: 0 auto
等价于以下内容:
margin-top: 0;
margin-bottom: 0;
margin-right: auto;
margin-left: auto;
实现垂直居中的解决方案
There are some options that you can utilize however to achieve vertical alignment despite the limitations. The easiest is to leverage a table. With tables, one of the few strong points of them is that using the vertical-align
property actually behaves as you would expect when enforced inside of a table. So you can do something like the following:
<body>
<table style="width: 100%; height: 100%">
<tr>
<td>
<div id="verticallyCenteredContent" style="vertical-align: middle">
OMG it's vertically aligned
</div>
<td>
<tr>
<table>
<body>
There are two other common methods that I demonstrated in this jsfiddle.
Useful article that demonstrates a number of scenarios and approaches for achieving vertical centering - Vertical Centering with Css
Cheers!