1

Don't mind the commented out lines. I'm experimenting with the box model, but can't seem to figure out why I can't use margin-top to drop the yellow box a bit down? I can use margin-left to get it to move to the right, so that seem weird to me... Thanks.

I'd like to understand why this happens :)

.largebox {
    width: 800px;
    height: 350px;
    background-color: #00f;
    //padding-left: 50px;
    margin-left: 10px;
    //border: 2px solid black;
}

.box1 {
    width: 250px;
    height: 300px;
    background-color: #ff0;
    //display: inline;
    //float: left;
    //margin-right: 0px;
    margin-left: 50px;
    margin-top: 25px;
 }
    <div class="largebox">
        <div class="box1"></div>

    </div>
kukkuz
  • 41,512
  • 6
  • 59
  • 95
JJLX
  • 97
  • 1
  • 10

3 Answers3

2

Use display:inline-block; in box1

.largebox {
    width: 800px;
    height: 350px;
    background-color: #00f;
    //padding-left: 50px;
    margin-left: 10px;
    //border: 2px solid black;
}

.box1 {
    width: 250px;
    height: 300px;
    background-color: #ff0;
    //display: inline;
    //float: left;
    //margin-right: 0px;
    margin-left: 50px;
    margin-top: 25px;
    display:inline-block;
 }
 
 
<div class="largebox">
        <div class="box1"></div>

    </div>
Afnan Ahmad
  • 2,492
  • 4
  • 24
  • 44
  • Thanks for your answer, could you explain to me why having the default display doesnt work? – JJLX Feb 03 '17 at 11:16
  • @Veen `inline-block` actually tells the browser to calculate the dimensions of the div after its placed and then those calculations are applied. – Afnan Ahmad Feb 03 '17 at 11:18
2

This happens due to margin collapsing - so a border, padding to the parent element or inline content (any inline element) will switch off margin collapsing.

See demo below:

.largebox {
  width: 800px;
  height: 350px;
  background-color: #00f;
  margin-left: 10px;
  border: 1px solid; /*ADDED THIS*/

}
.box1 {
  width: 250px;
  height: 300px;
  background-color: #ff0;
  margin-left: 50px;
  margin-top: 25px;
}
<div class="largebox">
  <div class="box1"></div>

</div>
kukkuz
  • 41,512
  • 6
  • 59
  • 95
0

You can try using position:absolute; in .box1 like this:

.box1{
    position:absolute;
}
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
shyamm
  • 506
  • 6
  • 17