25

So essentially does margin collapsing occur when you don't set any margin or padding or border to a given div element?

Marius
  • 57,995
  • 32
  • 132
  • 151
public static
  • 12,702
  • 26
  • 66
  • 86

2 Answers2

75

No. When you have two adjacent vertical margins, the greater of the two is used and the other is ignored.

So, for instance, if you have two block-display elements, A, followed by B beneath it, and A has a bottom-margin of 3em, while B has a top-margin of 2em, then the distance between them will be 3em.

If you set a border or padding, this prevents the collapsing from occurring. In the above example, the distance between the two elements will then be 5em.

If you don't set any margins, then there won't be any margins to collapse. It has nothing whatsoever to do with the element type in use - it is applicable to all element types, not just <div> elements.

Read the CSS 2.1 specification for more details.

Jim
  • 72,985
  • 14
  • 101
  • 108
  • 6
    Will upvote the answer, given a few changes: 1. In the '3em/2em' example, you might want to use absolute units instead; in this case, the 2em /could/ be greater than the 3em 2. "If you set a border or padding ..." - this is only true in certain cases, not in the standard 'A followed by B' one – Bobby Jack Jan 15 '09 at 11:56
  • 3. "If you don't set any ..." conventionally true for DIVs but margin-collapsing WILL affect most elements by default – Bobby Jack Jan 15 '09 at 11:58
  • 7
    +1 - good answer. Also, margin collapsing doesn't occur when elements are floated, absolutely positioned or inline-block. More info: http://reference.sitepoint.com/css/collapsingmargins – stephen.hanson Apr 23 '13 at 19:25
  • 1
    @steve.hanson ...or have `overflow: hidden` – matewka May 22 '14 at 13:15
  • this is only true if they are followed by each other, but not true, if you have a block element with a margin of 2em within an element that has no margin (0em), then the margin of the inner block element will still be 0em. So it won't always be the greater of the two. Eample: https://jsfiddle.net/56maenuL/ – Roland Jan 04 '17 at 20:06
4

"the expression collapsing margins means that adjoining margins (no non-empty content, padding or border areas or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin."

Source: Box Model - 8.3.1 Collapsing margins

Chris Serra
  • 13,226
  • 3
  • 25
  • 25