Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the impact of the negative bottom margin

Tags:

css

margin

First, here is the html:

<div class="first">
    <div class="second">
        <div class="third">
           Hello, margin collapsing!
        </div>
    </div>
</div>

Then here is the CSS:

.first {
  background-color: red;
  padding: 20px;
}

.second {
  background-color: green;
  margin-bottom: -20px;
}

.third {
  background-color: yellow;
  margin-bottom: 20px;
}

In the final layout, the third div looks like it doesn't have the bottom margin. I know it must be the effect of the second div whose bottom margin is negative. But I don't understand how it works. Could you please provide an explanation?

like image 300
Samuel Gong Avatar asked Nov 19 '25 00:11

Samuel Gong


1 Answers

Padding - Creates, easy said, a invisible border inside your element. You provide with it the spaces inside of your element (arround the content).

.first {
  background-color: red;
  padding: 20px;
}

So here you tell, any content of first hast to be 20px away from each side (each side cause you did not provide any declaration like padding-top)

Margin - On the other hand creates the opposite, it creates space arround your element.

.second {
  background-color: green;
  margin-bottom: -20px;
}

So this one says the second block has a space on the bottom outside. Its defined negative, which means the following items float in your element.

This explains it awfully: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model

like image 147
Doomenik Avatar answered Nov 21 '25 17:11

Doomenik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!