269

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?

Shawn
  • 47,241
  • 3
  • 26
  • 60
kjo
  • 33,683
  • 52
  • 148
  • 265

12 Answers12

338

There are two main types of margin collapse:

  • Collapsing margins between adjacent elements
  • Collapsing margins between parent and child elements

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:

  • float: left / right
  • position: absolute
  • display: flex / grid

You can test all of them here: http://jsfiddle.net/XB9wX/1/.

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.

Sources: Sitepoint's article Collapsing Margins

Mori
  • 8,137
  • 19
  • 63
  • 91
HQCasanova
  • 1,158
  • 1
  • 10
  • 15
80

One neat trick to disable margin collapsing that has no visual impact, as far as I know, is setting the padding of the parent to 0.05px:

.parentClass {
    padding: 0.05px;
}

The padding is no longer 0 so collapsing won't occur anymore but at the same time the padding is small enough that visually it will round down to 0.

If some other padding is desired, then apply padding only to the "direction" in which margin collapsing is not desired, 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>Border collapsing</h3>
<div class="parent">
  <div class="children">
  </div>
</div>

<h3>No border collapsing</h3>
<div class="parent noCollapse">
  <div class="children">
  </div>
</div>

Edit: changed the value from 0.1 to 0.05. As Chris Morgan mentioned in a comment bellow, and from this small test, it seems that indeed Firefox takes the 0.1px padding into consideration. Though, 0.05px seemes to do the trick.

Nicu Surdu
  • 8,172
  • 9
  • 68
  • 108
  • 2
    This is my favorite solution. You could even include this as a default style. Why not? `*{padding-top:0.1px}`. Are we sure it works in all browsers though? – Nick Manning Feb 18 '16 at 19:07
  • Worked pretty nice so far for me, but I don't claim to have tested it thoroughly in most browsers. – Nicu Surdu Feb 23 '16 at 22:35
  • 2
    Very nice solution, it seems to work as expected on most browsers. Thanks for sharing it! – wiredolphin Feb 24 '16 at 09:09
  • 3
    This is a dodgy solution as it *does* add extra pixels in various circumstances, due to high-DPI displays and subpixel calculations. (Firefox has done subpixel layout for ages, I believe other browsers have comparatively recently followed suit.) – Chris Morgan Sep 26 '17 at 02:04
  • `0.05px` seems still like a specific choice, not a random browser trickery number, I'd prefer `0.01px`. – Volker E. Jun 02 '20 at 01:39
  • `.01px` is too low and doesn't work (at least in Chrome). `.05px` seems to work the most consistently for now, and is still mostly imperceptible. Depending on layout, `margin-top: -.05px` may be an option to offset the padding, if it's super critical. – Chase Jan 10 '22 at 01:21
  • Just for completion: `0.01px` works in latest Chrome 102 and Firefox 102 on macOS. – Volker E. Jul 15 '22 at 17:31
  • 1
    This solution seems too clever, it is not so easy to understand compared to other options, so it has no place in the production code – MTpH9 Oct 28 '22 at 17:41
  • This answer is outdated, use `display: flex-root` – anthumchris Nov 30 '22 at 17:21
  • Only works for parent-child situations and not peer-peer elements. – Jason Cheng Jul 27 '23 at 03:16
69

You can also use the good old micro clearfix for this.

#container::before, #container::after{
    content: ' ';
    display: table;
}

See updated fiddle: http://jsfiddle.net/XB9wX/97/

tjbp
  • 3,427
  • 3
  • 24
  • 35
Blackgrid
  • 790
  • 5
  • 6
  • Have turned my answer into a community wiki. Please feel free to extend it with your answer. Thanks. – HQCasanova Oct 24 '14 at 20:43
  • 7
    I don't get it, when I view that example the margins are collapsing (only 10px vertical space between the divs instead of 20px) – Andy May 14 '15 at 02:25
  • 1
    This helps only in removing the collapse between siblings that all have this clearfix applied. I've forked the example to demonstrate this: http://jsfiddle.net/dpyuyg07/ --- and even that is not the whole story. It only removes the collapse of margins stemming from children of the elements where you've applied that fix. If you would add a margin on the container itself the margins would still collapse, which can be seen in this fork: http://jsfiddle.net/oew7qsjx/ – NicBright Jun 19 '15 at 14:07
  • 5
    I can put this even more precisely: the clearfix method only prevents margin collapse between parents and children. It does not affect the collapse between adjacent siblings. – NicBright Jun 19 '15 at 14:14
  • I think I now understand Bootstrap's tendency to fill the DOM with `:before` and `:after` elements. I have now added this rule to my stylesheet: `div:before, div:after{content: ' '; display: table;}`. Fantastic. Suddenly stuff starts to behave as expected. – Stijn de Witt Dec 02 '15 at 13:15
  • The margin is still collapsing for me in both Chrome and Firefox: https://imgur.com/a/Xv18D – Chris Smith Sep 09 '17 at 17:57
  • Does not work for self-closing element, such as ``. – Rockallite Sep 13 '17 at 01:04
27

Actually, there is one that works flawlessly:

display: flex; flex-direction: column;

as long as you can live with supporting only IE10 and up

.container {
  display: flex;
  flex-direction: column;
    background: #ddd;
    width: 15em;
}

.square {
    margin: 15px;
    height: 3em;
    background: yellow;
}
<div class="container">
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
</div>
<div class="container">
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
</div>
Daniel Koster
  • 421
  • 4
  • 6
  • 1
    For this to work as a generic solution, one has to add an extra `
    ` within the `.container`, otherwise the `.container` will control the box-model of its children. For example, inline elements will become full-width block elements; if they have margins those will also be margin-collapsed.
    – zupa Sep 19 '19 at 06:35
24

overflow:hidden prevents collapsing margins but it's not free of side effects - namely it... hides overflow.

Apart form this and what you've mentioned you just have to learn live with it and learn for this day when they are actually useful (comes every 3 to 5 years).

Litek
  • 4,888
  • 1
  • 24
  • 28
  • Have turned my answer into a community wiki. I think I did cover the side-effect you mentioned in the last two lines of the second paragraph: _Perhaps the only difference when using hidden is the unintended consequence of hiding content if the parent has a fixed height_. But if you feel that needs further clarification, please feel free to contribute. Thanks. – HQCasanova Oct 24 '14 at 20:41
  • 7
    `overflow: auto` is good to use to prevent hidden overflow and still prevent collapsing margins. – Gavin Jun 17 '15 at 15:01
  • 1
    @Gavin, `overflow:auto;` made my content area gain a scrollbar on some pages. – Reed Feb 18 '20 at 21:10
9

I know that this is a very old post but just wanted to say that using flexbox on a parent element would disable margin collapsing for its child elements.

Hesam
  • 146
  • 1
  • 6
9
CSS* Fixes
display: flow-root;
✅ Parent element collapse
❌ Sibling element collapse
display: flex;
flex-direction: column;
✅ Parent element collapse
✅ Sibling element collapse

*Modern browsers (excluding IE11) support display: flow-root and display: flex.

Examples

section {
  background: green;
  outline: 2px solid purple;
}

p {
  background: yellow;
  margin: 1em 0;
}

section.flow-root {
  display: flow-root;
}

section.flex {
  display: flex;
  flex-direction: column;
}
<h2>Default</h2>  
<section>
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
</section>

<h2><code>flow-root</code> (Fixes only container)</h2>
<section class="flow-root">
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
</section>

<h2><code>flex</code> (Fixes both container & siblings)</h2>
<section class="flex">
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
</section>
anthumchris
  • 8,245
  • 2
  • 28
  • 53
Chuanqi Sun
  • 1,123
  • 14
  • 26
  • Thanks for the edit [AnthumChris](https://stackoverflow.com/users/4035845/anthumchris). This makes me wonder if there is any technique that prevent Sibling collapse while preserving the Parent element collapse. That would make our answer the most flexible and complete solution! – Chuanqi Sun Dec 07 '22 at 03:19
8

Every webkit based browser should support the properties -webkit-margin-collapse. There are also subproperties to only set it for the top or bottom margin. You can give it the values collapse (default), discard (sets margin to 0 if there is a neighboring margin), and separate (prevents margin collapse).

I've tested that this works on 2014 versions of Chrome and Safari. Unfortunately, I don't think this would be supported in IE because it's not based on webkit.

Read Apple's Safari CSS Reference for a full explanation.

If you check Mozilla's CSS webkit extensions page, they list these properties as proprietary and recommend not to use them. This is because they're likely not going to go into standard CSS anytime soon and only webkit based browsers will support them.

Neil
  • 8,925
  • 10
  • 44
  • 49
Dan Carter
  • 587
  • 5
  • 8
  • This is nice because it helps us iron out an inconsistency in how Safari and Chrome deal with margins. – bjudson Jun 19 '15 at 22:44
  • 2
    Looks like the property `-webkit-margin-collapse` was removed in Chrome v85. I used this in some tools and the tests are now failing. – Möhre Oct 02 '20 at 10:14
3

To prevent margin collapsing between siblings, add display: inline-block; to one of the siblings (one is enough though you can add it to both).

GorvGoyl
  • 42,508
  • 29
  • 229
  • 225
3

Try

{
 display:flex;
 flex-direction:column;
}

or

{
   display:grid;
}
Mohit Kushwaha
  • 1,003
  • 1
  • 10
  • 15
2

I had similar problem with margin collapse because of parent having position set to relative. Here are list of commands you can use to disable margin collapsing.

HERE IS PLAYGROUND TO TEST

Just try to assign any parent-fix* class to div.container element, or any class children-fix* to div.margin. Pick the one that fits your needs best.

When

  • margin collapsing is disabled, div.absolute with red background will be positioned at the very top of the page.
  • margin is collapsing div.absolute will be positioned at the same Y coordinate as div.margin

html, body { margin: 0; padding: 0; }

.container {
  width: 100%;
  position: relative;
}

.absolute {
  position: absolute;
  top: 0;
  left: 50px;
  right: 50px;
  height: 100px;
  border: 5px solid #F00;
  background-color: rgba(255, 0, 0, 0.5);
}

.margin {
  width: 100%;
  height: 20px;
  background-color: #444;
  margin-top: 50px;
  color: #FFF;
}

/* Here are some examples on how to disable margin 
   collapsing from within parent (.container) */
.parent-fix1 { padding-top: 1px; }
.parent-fix2 { border: 1px solid rgba(0,0,0, 0);}
.parent-fix3 { overflow: auto;}
.parent-fix4 { float: left;}
.parent-fix5 { display: inline-block; }
.parent-fix6 { position: absolute; }
.parent-fix7 { display: flex; }
.parent-fix8 { -webkit-margin-collapse: separate; }
.parent-fix9:before {  content: ' '; display: table; }

/* Here are some examples on how to disable margin 
   collapsing from within children (.margin) */
.children-fix1 { float: left; }
.children-fix2 { display: inline-block; }
<div class="container parent-fix1">
  <div class="margin children-fix">margin</div>
  <div class="absolute"></div>
</div>

Here is jsFiddle with example you can edit

Buksy
  • 11,571
  • 9
  • 62
  • 69
0

For your information you could use grid but with side effects :)

.parent {
  display: grid
}
Whisher
  • 31,320
  • 32
  • 120
  • 201