使用不覆盖父元素的负百分比边距

Using negative % margin not covering parent element

既然在填充中使用 % 时,计算是基于父元素的宽度完成的,为什么 div 与父填充填充的负 % 不使 div覆盖整个父元素?

#test {
  max-width: 800px;
  width: 100%;
  margin: 0 auto;
  font-size: 12px;
  background: #fff;
  color: #000;
  line-height: 18px;
  border: 1px solid #000;
}

#test .content {
  padding: 2% 6%;
  text-align: justify;
}

#test .apply {
  margin-left: -6%;
  margin-right: -6%;
}

#test .apply p {
  font-family: Arial, Helvetica, sans-serif;
  text-align: center;
  background-color: yellow;
}
<div id="test">
  <div class="content">
    <p><strong>Test</strong></p>
    <div class="apply">
      <p>test</p>
    </div>
  </div>
</div>

准确的值应该是-6.81%而不是-6%。内层容器会考虑外层容器的内容区域(没有padding)1 来计算百分比。所以我们将有

0.06xW = px(1 - 0.06x2)xW  ==> p = 0.068181..

其中W#test的内容宽度,(1 - 0.06x2)xW.content的内容宽度,p是你需要使用的百分比负边距内:

#test {
  max-width: 800px;
  width: 100%;
  margin: 0 auto;
  font-size: 12px;
  background: #fff;
  color: #000;
  line-height: 18px;
  border: 1px solid #000;
}

#test .content {
  padding: 2% 6%;
  text-align: justify;
}

#test .apply {
  margin-left: -6.81%;
  margin-right: -6.81%;
}

#test .apply p {
  font-family: Arial, Helvetica, sans-serif;
  text-align: center;
  background-color: yellow;
}
<div id="test">
  <div class="content">
    <p><strong>Test</strong></p>
    <div class="apply">
      <p>test</p>
    </div>
  </div>
</div>

1The position and size of an element's box(es) are sometimes calculated relative to a certain rectangle, called the containing block of the element. The containing block of an element is defined as follows:

..

  1. For other elements, if the element's position is 'relative' or 'static', the containing block is formed by the content edge of the nearest block container ancestor box. ref