Add a Negative Margin to an Element - Why is the Margin Not Even?

Tell us what’s happening:
Can someone please explain why the margin above the green element appears narrower than below/left/right of the green element?

image

Your code so far

<style>
  .injected-text {
    margin-bottom: -25px;
    text-align: center;
  }

  .box {
    border-style: solid;
    border-color: black;
    border-width: 5px;
    text-align: center;
  }

  .yellow-box {
    background-color: yellow;
    padding: 10px;
  }
  
  .red-box {
    background-color: red;
    padding: 20px;
    margin: -15px;
  }

  .green-box {
    background-color: green;
    padding: 20px;
    margin: 20px;
  }
</style>

<div class="box yellow-box">
  <h5 class="box red-box">padding</h5>
  <h5 class="box green-box">padding</h5>
</div>

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/add-a-negative-margin-to-an-element

The margin of the h5 element with class=“box green-box” is the same on all four sides. The space between the top of the h5 element with class=box green-box" is narrower between it’s top border than the space between it’s bottom border and the bottom border of the div with class=“box yellow-box”, because of the -15px bottom margin of the red box plus the 5px of bottom border of the red box and 5px of top border of the green box. To make the green box appear centered vertically, you will need to account for that extra 25px of space.
Add the following top-margin to the .green-box css definition and it will be centered vertically like you are wanting.

    margin-top: 45px;
1 Like