How to disable margin folding
P粉530519234
P粉530519234 2023-08-21 23:21:12
0
2
452
<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>
P粉530519234
P粉530519234

reply all(2)
P粉521013123

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粉588660399

There are two main types of margin collapse:

  • Collapse of margins between adjacent elements
  • Margin collapse between parent element and child element

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template