Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Margin stacks on each other?

Tags:

css

margin

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

enter image description here

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:

enter image description here

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.
like image 258
deathlock Avatar asked Nov 05 '13 05:11

deathlock


People also ask

Can margins overlap?

In CSS, adjacent margins can sometimes overlap. This is known as “margin collapse”, and it has a reputation for being quite dastardly. This is an interactive element! Instead of sitting 48px apart, their 24px margins merge together, occupying the same space!

Do margins stack CSS?

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

Do horizontal margins add together?

They will not add up. Whichever is larger will be used.

How do I stop my margins collapsing?

How to Avoid Margin Collapse. First, remember that margins should preferably be used to increase the distance between sibling elements, not to create spacing between a child and a parent. If you need to increase space within the Flow layout, reach first for padding if possible.


1 Answers

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.
like image 98
Mr. Alien Avatar answered Nov 14 '22 16:11

Mr. Alien