Margin not working when parent element's padding is 0px

Hi guys, I’m new to HTML & CSS.
I’m facing an issue that I want to add margin to the blue “padding” box but in the end it doesn’t work.

Here is the code and result:

<style>
  .yellow-box {
    background-color: yellow;
    padding: 0px;
    <!--> padding: 1px; <-->
    <!--> border: 1px solid black; <-->
  }
  .blue-box {
    background-color: blue;
    color: #fff;
    margin: 10px;
  }
</style>
<div class="box yellow-box">
  <h5 class="box blue-box">padding </h5>
</div>

Snipaste_2021-03-23_18-08-04

The margin-top and margin-bottom are not applied.
Unless I set padding or border to its parent element(which is yellow box) as commented in the above code.

Appreciate if anyone can explain this to me.Preformatted text

Here is the result after adding 1px padding to yellow box:
Snipaste_2021-03-23_18-10-31

that’s because you style tag is open

I removed the tag purposely because I didn’t know how to post my original code.
Now I have edited the code with preformatted text in this post.

1 Like

The short answer is that vertical margins can collapse, horizontal margins can not collapse. This sometimes causes confusing behaviour even for people with a lot of CSS experience, but here’s an article that explains it really well:

@jsdisco Thank you very much for sharing this article with me. It is really helpful and solved my issue.

1 Like

did it work???[quote=“smilence97, post:4, topic:452487, full:true”]
I removed the tag purposely because I didn’t know how to post my original code.
Now I have edited the code with preformatted text in this post.
[/quote]

did it work

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.