Reputation: 5929
I have a scenario where I have multiple DIV stacked together with both margin-top and margin-bottom, but I found the margin-bottom ignored when I have margin-top. I couldn't explain how it happens.
html
<div class='box'>
<div class='item'>1</div>
<div class='item'>2</div>
<div class='item'>3</div>
<div class='item'>4</div>
<div class='item'>5</div>
<div class='item'>6</div>
<div class='item'>7</div>
<div class='item'>8</div>
</div>
css
.box{
width:100%;
height:300px;
}
.item{
list-style: none;
display:block;
margin-top:20px;
margin-bottom:20px;
width:100%;
height:50px;
background-color:red;
}
If I set the item to float:left, then it able to disable margin-bottom properly.
CSS by div floating left
.item{
list-style: none;
float:left;
display:block;
margin-top:20px;
margin-bottom:20px;
width:100%;
clear:both;
height:50px;
background-color:red;
}
Here's the jsfiddle link to illustrate it better. Tested with chrome and firefox. Could someone explain how it happens?
Upvotes: 2
Views: 1650
Reputation: 5719
To elaborate on my somewhat terse comment:
Imagine you have code like this:
<body>
<p>A paragraph</p>
<p>Another paragraph</p>
<p>A final paragraph</p>
</body>
and your CSS is:
p {
margin-top: 10px;
margin-bottom: 10px;
}
If the margin-collapsing didn't happen, you'd end up with a 10 pixel margin at the top, and a 10 pixel margin at the bottom, but 20 pixel margins between the paragraphs which is often not what was required.
To solve this, the browser collapses the top and bottom margins into each other so the gap between the paragraphs (or any other block-level elements) is equal to the larger of the top and bottom margins.
That's what's happening with your code.
Upvotes: 3