skip to Main Content
#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


  1. Your #child2 margin collapses with your parent margin. And as your parent 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 or child2 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…

    Login or Signup to reply.
  2. Dude, it works. If you add a sibling to your #parent, you’ll see this:

    #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;
    }
    
    #sibling {
      background-color: blue;
      height: 40px;
    }
    <div id="parent">
      <div id="child1">
        <div id="child2"></div>
      </div>
    </div>
    <div id="sibling"></div>

    P.S. Use classes instead of id

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search