2

I have the following HTML

<body>
    <div class="template">
        <div class="box"></div>
   </div>
</body>

My CSS

.template{
    height:500px;
    width:1000px;
    background-color:#e1bfbe;
    margin:0 auto;
}
.box{
    height:420px;
    width:165px;
    background-color:#ffffff;
    margin-left:416px;
    margin-right:417px;
    margin-top:37px;
    margin-bottom:38px;
}

Now I get the following output

enter image description here
but when I add float:left; in .box class I get the following image

enter image description here

only margin-top is not working without float:left; Why should I add float:left to get top margin for the element .box ?

vas
  • 962
  • 1
  • 9
  • 21
Joel
  • 49
  • 7
  • 1
    Your margin is being used on the parent element. See: http://stackoverflow.com/questions/1762539/margin-on-child-element-moves-parent-element – Curtis May 14 '15 at 05:11
  • 1
    Sounds like a case of collapsing margins. Check this thread out: http://stackoverflow.com/questions/9519841/why-does-this-css-margin-top-style-not-work – paradozx May 14 '15 at 05:16
  • I dont need a fixed code, I would like to know the reason....... – Joel May 14 '15 at 05:16

5 Answers5

2

Here's a thread that describes the same problem: CSS margin terror; Margin adds space outside parent element

It's a common issue with non-collapsing margins.

An alternative to adding float: left is overflow: auto

Community
  • 1
  • 1
DigitalDouble
  • 1,747
  • 14
  • 26
1

Add display: inline-block; to.box class.

Hardy
  • 542
  • 4
  • 10
1

Your margin is being used on the parent element and this is an expected behavior. However, there are a few ways to get around it...

Solution 1: Float the div... This will contain the margins of child elements and prevent margin collapsing.

Solution 2: You could also add a non-breaking space on the parent div

JSFiddle Demo

More info on collapsing margins can be found here.

Community
  • 1
  • 1
imbondbaby
  • 6,351
  • 3
  • 21
  • 54
0

Just add display:inline-block; to your box class margin-top would be again alive !

JSFiddle

CSS

.box {
    display:inline-block; /*Added */
    height:420px;
    width:165px;
    background-color:#ffffff;
    margin-left:416px;
    margin-right:417px;
    margin-top:37px;
    margin-bottom:38px;
}
divy3993
  • 5,732
  • 2
  • 28
  • 41
0

Try this I have Modified your Style little bit

html, body {
    margin:0;
}
.template {
    height:500px;
    width:100%;
    background-color:#e1bfbe;
    margin:0;
    float: left;
}
.box {
    height:420px;
    width:165px;
    background-color:#ffffff;
    margin: 37px auto;
}
<div class="template">
    <div class="box"></div>
</div>
Karthi Keyan
  • 804
  • 6
  • 18