0

I have this simple html and css

body{
  background-color: black;
  padding:0;
  margin: 0;
  box-sizing: border-box;
}

#ctr{
  height: 500px;
  width: 200px;
  margin: 0 auto;
  background-color: red;

}

#ctr > .box{
  background-color: white;
  height: 200px;
  width: 200px;
  border: 1px solid black;
  margin-top:10px;
}
<div id = "ctr">
  <div class = "box">
    <div class="something1"></div>
    <div class="something2"></div>
  </div>
</div>

I'm trying to add margin-top to the white box (box class) inside the red div(ctr id), but the whole red div is getting the margin and not just the white div.

here's a jsfiddle of the example. https://jsfiddle.net/6tvrwxhg/

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Morta1
  • 609
  • 7
  • 20
  • You have added a top margin of 10px, and that's moved `.box` down from the top of the viewport 10px... I don't know what your expectation is. – Mister Epic Jul 17 '16 at 13:14
  • try just to add position:absolute; to the .box class it will add the margin to the white box and the red one stay as is – nazimboudeffa Jul 17 '16 at 13:18

2 Answers2

1

Add overflow:auto (or hidden) to the parent (#ctr)

body {
  background-color: black;
  padding:0;
  margin: 0;
  box-sizing: border-box;
}

#ctr {
  height: 500px;
  width: 200px;
  margin: 0 auto;
  background-color: red;
  overflow: auto;
}

#ctr > .box{
  background-color: white;
  height: 200px;
  width: 200px;
  border: 1px solid black;
  margin-top:10px;
}
<div id="ctr">
  <div class="box">
    <div class="something1"></div>
    <div class="something2"></div>
  </div>
</div>

more info in a good answer

https://www.w3.org/TR/CSS2/box.html#collapsing-margins

Community
  • 1
  • 1
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
1

That is Parent/First child margin collapsing, and that happens if there is no border, padding, inline content or clearance to separate parent and child. So you can add border-top on parent

body {
  background-color: black;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
#ctr {
  height: 500px;
  width: 200px;
  margin: 0 auto;
  background-color: red;
  border-top: 1px solid transparent;
}
#ctr > .box {
  background-color: white;
  height: 200px;
  width: 200px;
  border: 1px solid black;
  margin-top: 10px;
}
<div id="ctr">
  <div class="box">
    <div class="something1"></div>
    <div class="something2"></div>
  </div>
</div>

Or you can add padding to parent element or use overflow: hidden

body {
  background-color: black;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
#ctr {
  height: 500px;
  width: 200px;
  margin: 0 auto;
  background-color: red;
  overflow: hidden
}
#ctr > .box {
  background-color: white;
  height: 200px;
  width: 200px;
  padding-top: 1px;
  margin-top: 10px;
}
<div id="ctr">
  <div class="box">
    <div class="something1"></div>
    <div class="something2"></div>
  </div>
</div>

You can read more about this at Mastering margin collapsing

Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176