0px(但不是 0.1px)填充容器内的负边距

Negative margin inside a 0px (but not 0.1px) padding container

当具有负边距的元素被放入具有 padding: 0 的元素内时,我遇到了意外行为,这是意外的,因为即使将填充设置为很小的 [=11=,也不会发生这种情况], 有效渲染 0 像素的填充。

我做了一个codepen来演示这个问题,使用按钮来改变填充。

我已经在 Chrome 上试过了。

它应该是这样工作的吗?如果是,为什么?

<div class="actions">
  <button onclick="set_padding ( 10 )">10px padding</button>
  <button onclick="set_padding ( 0,1 )">0.1px padding</button>
  <button onclick="set_padding ( 0 )">0 padding</button>
</div>

我把 0,1 放在 0.1 的位置,它起作用了

是的。这种行为称为 collapsing margin。引用 MDN:

If there is no border, padding, [...] to separate the margin-bottom of a block from the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.

你用你的填充切换这个on/off,尽可能小。现代浏览器从一段时间开始就进行亚像素渲染。