CSS:为什么容器上的填充或边框会改变封闭浮动的行为?
有人可以向我解释为什么向容器元素添加填充或边框会影响浮动 div 的显示方式吗?
样品1& 4 显示我所期望的。样品2& 3 不。
这真是让我抓狂了!
它在 Webkit 和 FireFox 中的行为都很奇怪。没有测试过IE。
<div style="">
<div style="border: 1px solid green; float: right;">This float is correct</div>
<h3 style="margin: 20px 0px; border: 1px solid blue;">Sample 1</h3>
<p>Parent has nothing</p>
</div>
<div style="padding: 1px;">
<div style="border: 1px solid green; float: right;">This float is incorrect</div>
<h3 style="margin: 20px 0px; border: 1px solid blue;">Sample 2</h3>
<p>Parent has padding</p>
</div>
<div style="border: 1px solid red;">
<div style="border: 1px solid green; float: right;">This float is incorrect</div>
<h3 style="margin: 20px 0px; border: 1px solid blue;">Sample 3</h3>
<p>Parent has border</p>
</div>
<div style="padding: 1px;">
<div style="border: 1px solid green; float: right;">This float is correct</div>
<h3 style="margin: 0px 0px; border: 1px solid blue;">Sample 4</h3>
<p>Parent has padding, H3 has no margin</p>
</div>
Can someone explain to my why adding either padding or border to a container element has an effect on how the floating div is displayed?
Sample 1 & 4 display how I expect. Sample 2 & 3 do not.
This is really driving me crazy!
It behaves strangely in both Webkit and FireFox. Have not tested IE.
<div style="">
<div style="border: 1px solid green; float: right;">This float is correct</div>
<h3 style="margin: 20px 0px; border: 1px solid blue;">Sample 1</h3>
<p>Parent has nothing</p>
</div>
<div style="padding: 1px;">
<div style="border: 1px solid green; float: right;">This float is incorrect</div>
<h3 style="margin: 20px 0px; border: 1px solid blue;">Sample 2</h3>
<p>Parent has padding</p>
</div>
<div style="border: 1px solid red;">
<div style="border: 1px solid green; float: right;">This float is incorrect</div>
<h3 style="margin: 20px 0px; border: 1px solid blue;">Sample 3</h3>
<p>Parent has border</p>
</div>
<div style="padding: 1px;">
<div style="border: 1px solid green; float: right;">This float is correct</div>
<h3 style="margin: 0px 0px; border: 1px solid blue;">Sample 4</h3>
<p>Parent has padding, H3 has no margin</p>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您所看到的是“边距崩溃”,当两个元素彼此重叠时就会发生这种情况。它消失的原因是您向其中一个元素添加了边框或轮廓。来自 W3C:
What you are witnessing is "margin collapse" which occurs when two elements are on top of each other. The reason it goes away is you add the border or outline to one of the elements. From the W3C:
我认为实际上 2、3 和 4 都按照应有的方式渲染,而 1 看起来有点奇怪。
overflow:hidden
添加到封装 div 似乎对其进行了排序,因此它尊重 h3 的边距。I think actually 2, 3 and 4 are rendered like they should be and 1 looks a bit weird.
overflow: hidden
to the encapsulating div seems to sort it so it respects the margin of h3.