Adjust the Padding of an Element

Tell us what’s happening:

why is the word ‘margin’ inside of the yellow box when in the code it’s not in the div? also if I rewrite the ‘margin’ line code to any text in the

element, it goes out, why?

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: crimson;
    color: #fff;
    padding: 20px;
  }

  .blue-box {
    background-color: blue;
    color: #fff;
    padding: 20px;
  }
</style>
<h5 class="injected-text">margin</h5>

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

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/responsive-web-design/basic-css/adjust-the-padding-of-an-element

It’s because of this code.

.injected-text {
margin-bottom: -25px;
}

Which puts the header downwards.

Margin moves an element around relative to its position. So giving something margins will move itself to whatever values you give to.

More specifically, it is because of the negative margin.

Using a negative top/bottom margin can be seen as pulling as opposed to a positive, which is pushing. But, you are right to be curious about why the margin div seems to be breaking into the box, that would otherwise, be a barrier, at least when talking about two statically positioned blocks. Using negative margin, is in fact, an alternative to relative/absolute positioning, well in some cases at least.

The assignment two assignments from the one you are on talks a bit about negative margin, unfortunately IMO it does a pretty bad job of it saying.

“If you set an element’s margin to a negative value, the element will grow larger.”

This is only true of the left/right negative margin, not top/bottom. It also doesn’t actually talk much (at all) about how or why to use negative margins.

Here is a pretty old but still relevant smashingmagazine article about using negative margins.