Margin stacks on each other?

2019-06-23 02:22发布

问题:

I have long noticed that when two block elements are put next to each other, their margin stacks on each other. Something like this:

Both <div>s have margin: 1em, but when margin1's margin-bottom collides with margin2's margin-top, both margin just stack on each other. See on here: http://jsfiddle.net/39XmC/

What I was expecting was something like this:

Both <div>s actually give spaces on each margin and doesn't stack on each other's margins.

I know that this can be fixed by floating or overflowing the element. My question:

  1. Why does this happen [theoretically]? Isn't margin not supposed to stack?
  2. Is this the default behavior on browsers? Because I remember working on a project that doesn't have this behavior.

回答1:

That behavior is normal and it's called as Collapsing Margins..

Quoting from W3C:

In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.

Adjoining vertical margins collapse, except:

  • Margins of the root element's box do not collapse.
  • If the top and bottom margins of an element with clearance are adjoining, its margins collapse with the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block.


回答2:

Its a property of CSS. Please refer this one

When you have

h1 {
  margin: 0;
  background: #cff;
}
div {
  margin: 40px 0 25px 0;
  background: #cfc;
}
p {
  margin: 20px 0 0 0;
  background: #cf9;
}

And html as

<h1>Heading Content</h1>
<div>
  <p>Paragraph content</p>
</div>

The margin top of the paragraph will be 40px and not 60px.



回答3:

As for the why this happens...

Margins aren't about sizing the element; they're only about breathing room. (You may notice that even box-sizing won't let you consider the margin as part of the element's size. Because it's not.)

A margin of 1em means "I need at least 1em of space around myself to not look crowded." If you have two elements next to each other that both say they want at least 1em of space, then spacing them 1em apart satisfies both conditions while wasting the minimum amount of space. The rules for collapsing margins make a lot more sense if you keep this in mind.



标签: css margin