P K
P K

Reputation: 10210

Margin collapse issue between div

I'm expecting the vertical gap between bottom border of first div and top border of second div to be 45px in this case but browser collapse bottom and top margin.

Effective gap b/w bottom border of first div and top border of second div in browser display is 25px.

Ideally border should prevent margin collapse. What is the mistake here? I have not applied any positioning or float.

jsfiddle Code

HTML

<body>
<div><p>A</p></div>
<div><p>B</p></div>
</body>

CSS

div{
    width:200px;
    height:200px;
}
div:nth-child(1){
    background-color: #F52C6F; 
    border-bottom: 10px solid black;
    margin-bottom: 20px;
}
div:nth-child(2){
    background-color: #0ECCCC; 
    border-top: 10px solid yellow;
    margin-top: 25px;
}

Upvotes: 3

Views: 2601

Answers (3)

BoltClock
BoltClock

Reputation: 723688

Ideally border should prevent margin collapse. What is the mistake here? I have not applied any positioning or float.

Borders do not block margin collapse between siblings — they only block margin collapse between a parent and a child, or wherever the borders would otherwise intersect the margins.

From the spec:

Two margins are adjoining if and only if:

  • ...
  • no line boxes, no clearance, no padding and no border separate them
  • ...

Since the borders aren't actually separating or intersecting the margins between your two div elements, the margins are considered adjoining, and therefore margin collapse occurs between them as usual. The borders on your div elements would however prevent margins of your divs collapsing with those of their p children.

Upvotes: 6

Gimmy
Gimmy

Reputation: 3911

Try somthing like this:

Html:

<body>
    <div id="parent">
<div><p>A</p></div>
<div><p>B</p></div>
    </div>
</body>

CSS:

#parent
{
    width:200px;
    height:200px;
}
#parent div:nth-child(1){
    background-color: blue; 
    border-bottom: 10px solid black;
    margin-bottom: 20px;
  }
#parent div:nth-child(2){
    background-color: green; 
    border-top: 10px solid yellow;
  }

And here is a working jsFiddle: http://jsfiddle.net/hEDR3/

Upvotes: 0

Nils Kaspersson
Nils Kaspersson

Reputation: 9464

This behaviour is actually documented in the W3C Specification on the box model: Collapsing Margins.

Basically, adjoining vertical margins collapse into one margin, where the larger margin value is used and the lower value is discarded.

Use one higher margin value instead of two lower. :-)

Upvotes: 0

Related Questions