html - 为什么 CSS 左右边距会增加元素的大小?

标签 html css

我有以下代码:

* {
  box-sizing: border-box;
}

.blue {
  color: #fff;
  background-color: blue;
  flex: 0 0 50%;
  max-width: 50%;
  padding: 0 15px;
}

.violet {
  color: #fff;
  background-color: blueviolet;
  flex: 0 0 50%;
  max-width: 50%;
  padding: 0 15px;
}

.div {
  background: black;
  color: white;
  margin: 50px auto;
  display: flex;
  margin-left: -15px;
  margin-right: -15px;
}

.xont {
  width: 60%;
  margin: auto;
  padding-left: 15px;
  padding-right: 15px;
}
<div class="xont">
  <div class="div">
    <div class="violet">This is div 1</div>
    <div class="blue">This is div 2</div>
  </div>
</div>

为什么 .div 元素的宽度增加了 30px 当我将左右的负边距设置为 -15px 时?

最佳答案

这里是规范中描述如何计算 block 元素宽度的部分:https://www.w3.org/TR/CSS21/visudet.html#blockwidth .

公式为:

The following constraints must hold among the used values of the other properties:

'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block

您还可以阅读:

If 'width' is set to 'auto', any other 'auto' values become '0' and 'width' follows from the resulting equality.

所以填充和边框我们是 0,我们将有:

'margin-left' + 'width' + 'margin-right' = 包含 block 的宽度

然后

'width' = 包含 block 的宽度 - 'margin-left' - 'margin-right'

现在很清楚,如果边距为负,则元素的宽度将增加到超过包含 block 的宽度。

关于html - 为什么 CSS 左右边距会增加元素的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55664770/

相关文章:

javascript - 使用 map 显示 JSON 数据时,Reactjs 出现错误?

javascript - 如何使用 slider 更改 HTML5 音频音量或轨道位置?

javascript - HTML JavaScript - div 元素在 Chrome 和 Safari/Firefox 之间的工作方式不同

css - 在 Shiny 按钮上应用 2 种不同的 CSS 样式

css - HTML 中的跨浏览器网格系统

html - 如何摆脱烦人的 iframe 边框?

html - 根据屏幕分辨率调整图像大小的简单方法

html - 元素符号列表与 css 属性/值列不一致 : 2;

html - 在 :hover 上的图像上显示 <div> 或 <span>

html - 流动柱和固定柱