Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS margins add up or are combined?

Tags:

css

margin

Let's assume that we have the following code:

<div style="margin-bottom:100px;">test</div>
<div style="margin-top:100px;">test</div>

I noticed that sometimes it creates 100px of margin between elements and sometimes it's 200px (when we use certain settings that I'm not familiar with). I can't find any information about that in the specification. What does this depend on?

If we have h1 and p in a blank document then the margin of h1 will be combined with the margin of p. They will not add up. Whichever is larger will be used.

like image 997
Atadj Avatar asked Feb 05 '13 09:02

Atadj


People also ask

Do margins stack CSS?

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. Margins of the root element's box do not collapse.

Do margins overlap CSS?

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!

What does margin do when added to the CSS?

The CSS margin properties are used to create space around elements, outside of any defined borders. With CSS, you have full control over the margins. There are properties for setting the margin for each side of an element (top, right, bottom, and left).


1 Answers

This is happening because your margins are allowed to collapse. Certain margins may overlap (mostly block elements) and form a combined margin defined by the larger of the two values defined in the computed element style rules - that's what is happening here. This section from the CSS Box Model document explains it in detail.

Edit: As a point of interest, you can get around this (ie. break the collapsible margins) without breaking things (much?)in a couple of ways

  • Making the elements width: 100%; display: inline-block
  • Putting a height: 0; width: 0; overflow: hidden block in between the elements and putting a dot or something in it.

I forked ashley's fiddle to demonstrate. There are probably other methods but these are a quick a dirty way to get around collapsible margins if you need to.

like image 53
m.brindley Avatar answered Oct 11 '22 15:10

m.brindley