Morta 1 Morta 1 - 4 months ago 15
CSS Question

margin of an element

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/

Answer

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