Margin-top/bottom 不适用于示例中的 margin-left/right

Margin-top/bottom not works the to margin-left/right in a sample

我是 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" 水平居中。

然后我将宽度更改为高度,并将 margin-left/right 更改为 margin-top/bottom。 (下面的代码)

<!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>

它没有像我预期的那样垂直居中。

任何人都可以帮我解释一下,为什么他们没有相同的行为? 谢谢, 黄

margin-auto 仅适用于水平边距。即 margin-left and right.

无法将垂直边距设置为自动。相反,您可以将其设为内联块并将其设置为垂直居中。阅读 this answer

MDN says:

margin: auto;  /* box is horizontally centered, 0 margin on top and bottom */

下面我试过了

<!DOCTYPE html>

<html style="height:100%">
<head>
<title>Center</title>
</head>

<body style="height:100%; width:100%">
    <div style="display:table; width:100%; height:100%">
        <div id="div1" style="display:table-cell;vertical-align:middle">
            <div id="div2" style="display:table-cell;vertical-align:middle;height:20px; margin:0 auto; background-color:gray">Text is vertical alignment</div>
        </div>
    </div>  
</body>

</html>