Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would two empty divs with only margins collapse?

Tags:

html

css

How would two empty divs with only margins collapse?

html file:

<div id="div1"></div>
<div id="div2"></div>

CSS File:

#div1 {
  margin-top: 10px;
  margin-bottom: 20px;
}

#div2 {
  margin-top: 10px;
  margin-bottom: 30px;
}

Thanks.

like image 426
Django102 Avatar asked Aug 01 '18 01:08

Django102


People also ask

Why does margin collapse happen?

Margin collapse occurs when vertically adjacent margins of block-level elements collide to share a general margin space. The size of this shared space is dictated by the larger number margin.

In which scenario margins will collapse?

If there is no border, padding, inline content, height , or min-height to separate a block's margin-top from its margin-bottom , then its top and bottom margins collapse. Some things to note: More complex margin collapsing (of more than two margins) occurs when the above cases are combined.

Why is margin not collapsing?

Margins of elements do not collapse when the value of the overflow property of the elements is set to anything other than visible. Its value must be visible so that margin can collapse.

Why left and right margins do not collapse in CSS?

In CSS2, only vertical margins are specified to collapse — that is the top and bottom margins on an element if you are in a horizontal writing mode. So the left and right margins above are not collapsing and ending up outside the wrapper.


1 Answers

The answer is:

You will have only 30px margin at the end

You are facing two kind of margin collpasing. Since each div is empty, its top margin and bottom margin will collapse so for the first one we will have 20px and for the second one 30px. Then those margin will also collapse together and will end with only 30px.

You can verify this by checking the height of the html element and you will see this:

#div1 {
  margin-top: 10px;
  margin-bottom: 20px;
}

#div2 {
  margin-top: 10px;
  margin-bottom: 30px;
}
<div id="div1"></div>
<div id="div2"></div>

enter image description here

From the sepcification:

top and bottom margins of a box that does not establish a new block formatting context and that has zero computed 'min-height', zero or 'auto' computed 'height', and no in-flow children

And

bottom margin of box and top margin of its next in-flow following sibling


As a side note, the body has also a default margin (8px) collapsing with other other margin following this rule:

top margin of a box and top margin of its first in-flow child

And

bottom margin of a last in-flow child and bottom margin of its parent if the parent has 'auto' computed height

like image 104
Temani Afif Avatar answered Nov 15 '22 21:11

Temani Afif