<分区>
<分区>
我一直想知道为什么我可以对左/右使用 margin auto 来水平居中 div,而不是垂直居中。在这里我希望垂直居中:div-block-vertical-line 但 margin-top 和 margin-bottom 不起作用。
.div-block-container {
width: 2%;
height: 300px;
background: red;
}
.div-block-vertical-line {
display: block;
width: 2px;
height: 90%;
margin-right: auto;
margin-left: auto;
margin-top: auto;
margin-bottom: auto;
background: blue;
}
<div class="div-block-container">
<div class="div-block-vertical-line"></div>
</div>
最佳答案
如果你勾选the MDN page :
auto
The browser selects a suitable margin to use. For example, in certain cases this value can be used to center an element.
因此,如果您使用 auto
,您的浏览器将简单地选择 0
作为上边距/下边距。
在 the specification 中:
If 'margin-top', or 'margin-bottom' are 'auto', their used value is 0
您要查找的内容在 flexbox model 中定义:
Auto margins on flex items have an effect very similar to auto margins in block flow:
During calculations of flex bases and flexible lengths, auto margins are treated as 0.
Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.
Overflowing boxes ignore their auto margins and overflow in the end direction
.div-block-container {
width: 2%;
height: 300px;
background: red;
display:flex;
}
.div-block-vertical-line {
display: block;
width: 2px;
height: 90%;
margin-right: auto;
margin-left: auto;
margin-top: auto;
margin-bottom: auto;
background: blue;
}
<div class="div-block-container">
<div class="div-block-vertical-line"></div>
</div>
所以为什么没有特别的原因。它就是这样简单地定义的,后来在引入 flexbox 时得到了增强。
关于html - 为什么边距自动适用于左/右而不适用于顶部/底部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51609480/