如何禁用边距折叠? [英] How to disable margin-collapsing?
问题描述
有没有办法完全禁用边距折叠?我发现的唯一解决方案(以uncollapsing"为名)需要使用 1px 边框或 1px 填充.我觉得这是不可接受的:无关的像素无缘无故地使计算复杂化.有没有更合理的方法来禁用这种边距折叠?
Is there a way to disable margin-collapsing altogether? The only solutions I've found (by the name of "uncollapsing") entail using a 1px border or 1px padding. I find this unacceptable: the extraneous pixel complicates calculations for no good reason. Is there a more reasonable way to disable this margin-collapsing?
推荐答案
边距折叠主要有两种类型:
There are two main types of margin collapse:
- 折叠相邻元素之间的边距
- 折叠父元素和子元素之间的边距
仅在后一种情况下使用填充或边框才能防止折叠.此外,任何与应用于父级的默认值 (visible
) 不同的 overflow
值都将防止崩溃.因此,overflow: auto
和 overflow: hidden
将具有相同的效果.也许使用 hidden
的唯一区别是如果父级具有固定高度,则隐藏内容的意外后果.
Using a padding or border will prevent collapse only in the latter case. Also, any value of overflow
different from its default (visible
) applied to the parent will prevent collapse. Thus, both overflow: auto
and overflow: hidden
will have the same effect. Perhaps the only difference when using hidden
is the unintended consequence of hiding content if the parent has a fixed height.
一旦应用于父级,可以帮助修复此行为的其他属性是:
Other properties that, once applied to the parent, can help fix this behaviour are:
浮动:左/右
位置:绝对
display: inline-block/flex
您可以在这里测试所有这些:http://jsfiddle.net/XB9wX/1/.
You can test all of them here: http://jsfiddle.net/XB9wX/1/.
我应该补充一点,像往常一样,Internet Explorer 是个例外.更具体地说,在 IE 7 中,当为父元素指定某种布局(例如 width
)时,边距不会折叠.
I should add that, as usual, Internet Explorer is the exception. More specifically, in IE 7 margins do not collapse when some kind of layout is specified for the parent element, such as width
.
来源:Sitepoint 的文章折叠边距
Sources: Sitepoint's article Collapsing Margins
这篇关于如何禁用边距折叠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!