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

标签 css margin padding

既然在padding中使用%是根据父元素的宽度计算的,为什么父padding fill为负%的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%。内部容器会考虑外部容器的内容区域(没有填充)1 计算百分比。所以我们将有

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

其中W#test的内容宽度,(1 - 0.06x2)xW的内容宽度。 contentp 是您需要在负边距内使用的百分比:

#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

关于css - 使用不覆盖父元素的负百分比边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59716694/

相关文章:

html - css 边距超过页面布局(高度)

java - Android - 如何以编程方式在 LinearLayout 中添加多个具有不同布局边距的按钮?

c - 编译器如何处理错位?

javascript - 如何使信息框在点击时出现在网站上

css - 是否可以将固定布局网站转换为响应式网站

css - adminlte rails 侧边栏无法正常工作

css - css 中边距的默认值

css - 显示 : table-cell extends outside parent 内的多个元素、填充和边距

margin - 如何在 Bootstrap 3 网格系统中调整装订线?

css - 具有过渡的跨浏览器兼容框阴影