P粉5210131232023-08-22 17:46:33
A neat trick to disable margin collapsing that has no visual impact, as far as I know, is to set the parent element's padding to 0.05px
:
.parentClass { padding: 0.05px; }
The padding is no longer 0, so no folding occurs, but at the same time the padding is small enough that it is visually rounded to 0.
If additional padding is required, apply padding only in the "direction" where you do not want margin collapse to occur, for example padding-top: 0.05px;
.
Working example:
.noCollapse {
padding: 0.05px;
}
.parent {
background-color: red;
width: 150px;
}
.children {
margin-top: 50px;
background-color: lime;
width: 100px;
height: 100px;
}
<h3>边框折叠</h3>
<div class="parent">
<div class="children">
</div>
</div>
<h3>无边框折叠</h3>
<div class="parent noCollapse">
<div class="children">
</div>
</div>
Edit: Changed value from 0.1
to 0.05
. As Chris Morgan mentioned in the comments below, and as can be seen from this little test, it seems that Firefox does consider 0.1px
padding. However, 0.05px
seems to work.
P粉5886603992023-08-22 16:36:44
There are two main types of margin collapse:
Only in the latter case, using padding or borders will prevent folding. Additionally, any overflow
attribute applied to a parent element that is different from its default value (visible
) will prevent folding. Therefore, overflow: auto
and overflow: hidden
will have the same effect. Maybe the only difference when using hidden
is that the content will be hidden unexpectedly if the parent element has a fixed height.
Some other properties that can help fix this behavior when applied to the parent element are:
float: left / right
position: absolute
display: flex / grid
You can test them here: http://jsfiddle.net/XB9wX/1/.
I should add that, as usual, Internet Explorer is the exception. Specifically, in IE 7, when a certain layout (such as width
) is specified for the parent element, the margins do not collapse.
Source: Sitepoint articleCollapse margin