#parent {
background-color: blue;
margin-bottom: 40px;
margin-top: 40px;
}
#child1 {
background-color: red;
}
#child2 {
height: 200px;
background-color: yellow;
margin-top: -40px;
margin-bottom: -40px;
}
<div>
<div id="parent">
<div id="child1">
<div id="child2"></div>
</div>
</div>
</div>
the margin-bottom on child2 is not working even though the property is being applied on the div. Someone please help me.
I need to somehow cancel the margin added by parent by adding negative margin-bottom to child2
Please use https://jsfiddle.net/nishantmudgal/wy2b7eg9/1/ to try it as somehow the issue is not reproduced on above snippets.
2
Answers
Your
#child2
margin collapses with yourparent
margin. And as yourparent
margin is the biggest of the 2, `#child2’s margin is ignored.Margin collapses are a bit tricky, you can find a detailed explanation here:
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_box_model/Mastering_margin_collapsing
My guess is that the collapse happens because you don’t have content between your parents and your descendants, i.e. you can probably stop it by adding a padding, border etc. to
child1
orchild2
for instance.That being said, "cancelling" a margin with anothe rmargin sounds like a hack, and it will for sure make your code less readable. I don’t know your specific use case, but I’d consider alternatives…
Dude, it works. If you add a sibling to your
#parent
, you’ll see this:P.S. Use classes instead of id