How to disable margin folding
P粉530519234
2023-08-21 23:21:12
<p>Is there a way to completely disable margin folding? The only solution I found (named "uncollapsing") is to use a 1 pixel border or a 1 pixel padding. I find this unacceptable: extra pixels complicate calculations unnecessarily. Is there a more reasonable way to disable this margin collapsing? </p>
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
: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:
Edit: Changed value from
0.1
to0.05
. As Chris Morgan mentioned in the comments below, and as can be seen from this little test, it seems that Firefox does consider0.1px
padding. However,0.05px
seems to work.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
andoverflow: hidden
will have the same effect. Maybe the only difference when usinghidden
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