html - 为什么边距自动适用于左/右而不适用于顶部/底部?

标签 html css margin

<分区>

我一直想知道为什么我可以对左/右使用 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/

上一篇:javascript - CSS 网站适合设备的宽度

下一篇:html - 将面板设置为低于图像 < 768px

相关文章:

css - 元素宽度 :100% not working with container/container-fluid

html - 如何制作左边是logo,右边是导航的header?

css - 需要制作一个可点击的 <div> 按钮

html - 如何识别页面顶部的这个奇怪的空白区域?

javascript - 尝试将服务注入(inject)组件

css - 自动调整背景颜色以覆盖整个容器

jquery - 开始搜索时显示 Press Enter

php - 仅在主页上透明的导航栏(Php 和 CCS)

latex - 动词/lstinline 文本在 Latex 中没有换行符而流出行边距

html - 边界出 DIV (borde fuera de div)