为什么margin自动适用于左/右,而不适用于顶部/底部?

问题描述:

我一直想知道为什么我可以对左边/右边使用margin auto来水平居中div,而不能垂直居中.在这里,我希望垂直居中: div-block-vertical-line ,但是margin-top和margin-bottom无效.

I always wanted to know why I can use margin auto for left/right to horizontally center a div, and not for vertically center. Here I would have liked to vertically center : div-block-vertical-line but margin-top and margin-bottom won't work.

.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 browser selects a suitable margin to use. For example, in certain cases this value can be used to center an element.

因此,如果您使用 auto ,则浏览器只需选择 0 作为上/下边距.

So your browser will simply select 0 for top/bottom margin if you use auto.

以及规范:

如果'margin-top'或'margin-bottom'为'auto',则其使用值为0

If 'margin-top', or 'margin-bottom' are 'auto', their used value is 0


您要查找的内容在 flexbox模型中定义:

弹性项目上的自动边距效果与自动边距非常相似处于阻塞状态:

Auto margins on flex items have an effect very similar to auto margins in block flow:

在计算弹性基数和弹性长度时,自动页边距被视为0.

During calculations of flex bases and flexible lengths, auto margins are treated as 0.

在通过对齐内容和align-self进行对齐之前,任何肯定的可用空间在该维度上分配给自动页边距.

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时对其进行了增强.

So there is no particular reason for the why. It was simply defined like that and later enhanced when flexbox was introduced.