【发布时间】:2015-05-11 16:24:08
【问题描述】:
我是 HTML 和 CSS 的新手。 我试过下面的代码
<!DOCTYPE html>
<html>
<head>
<title>Center</title>
</head>
<body>
<div id="div1" style="width:300;background-color:olive">
<div id="div2" style="width:100px; margin-left:auto; margin-right:auto; background-color:gray"></div>
</div>
</body>
</html>
“div2”水平居中。
然后我将宽度更改为高度并将边距左/右更改为边距顶部/底部。 (下面的代码)
<!DOCTYPE html>
<html>
<head>
<title>Center</title>
</head>
<body>
<div id="div1" style="height:100px;background-color:olive">
<div id="div2" style="height:20px; margin-top:auto; margin-bottom:auto; background-color:gray"></div>
</div>
</body>
</html>
它没有像我预期的那样垂直居中。
任何人都可以帮我解释一下,为什么他们没有相同的行为? 谢谢, 黄
【问题讨论】:
-
垂直居中不像水平那么容易。
auto对margin-top/bottom什么都不做。 -
你知道为什么它的行为与逻辑不同吗?
-
我不是 CSS 规范的作者,但作为一名开发人员,我从来不需要通过这种方式垂直居中