既然在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
是的内容宽度。 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:
..
- 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/