-1

Output

body {
  margin: 0;
  width: 100%;
  height: 2000px;
  background-color: rgb(47, 224, 255);
}

.container {
  width: 100%;
  height: 2000px;
  background-color: rgb(34, 34, 241);
  
}

.child1 {
  width: 45%;
  height: 15%;
  background-color: crimson;
  margin: 20px;
}
<body>
  <div class="container">
    <div class="child1"></div>
  </div>
</body>

This code displays above output. Margin of child div is affect in the container div. Why this happens?

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Ansif TC
  • 1
  • 3
  • Here's [a JSFiddle](https://jsfiddle.net/8sfdp1b9/) of the code above. My guess is that the margins seem inconsistent, there's one of the left, of the innermost `DIV`, but not at the top. This is probably due to [margin collapse](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing). But to be honest, I don't quite get the question. – KIKO Software Feb 18 '22 at 11:38

2 Answers2

-1

This is because the Child div is part of the container div, so the margin applies to all divs inside a div

-1

I think this is indeed due to Margin Collapse as mentioned by KIKO Software. Because there is no content in the container If you add for example some text in the container div, the margins seem to be equal all sides. If you want to leave the container empty, you can set display: inline-block on the container element and you will end up with equal margins.

Info from MDN:

No content separating parent and descendants If there is no border, padding, inline part, block formatting context created, or clearance to separate the margin-top of a block from the margin-top of one or more of its descendant blocks; or no border, padding, inline content, height, or min-height to separate the margin-bottom of a block from the margin-bottom of one or more of its descendant blocks, then those margins collapse. The collapsed margin ends up outside the parent.

body {
  margin: 0;
  width: 100%;
  height: 2000px;
}

.container {
  width: 100%;
  height: 2000px;
  background-color: rgb(34, 34, 241);
  background-color: rgb(47, 224, 255);
  display: inline-block;
}

.child1 {
  width: 45%;
  height: 15%;
  background-color: crimson;
  margin: 20px;
}
<body>
  <div class="container">
    <div class="child1"></div>
  </div>
</body>
MC-SO
  • 21
  • 6