Reputation: 59
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
but when I add float:left;
in .box
class I get the following image
only margin-top is not working without float:left;
Why should I add float:left
to get top margin for the element .box ?
Upvotes: 2
Views: 245
Reputation: 804
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>
Upvotes: 0
Reputation: 6411
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
More info on collapsing margins can be found here.
Upvotes: 1
Reputation: 1768
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
Upvotes: 2
Reputation: 5810
Just add display:inline-block; to your box class margin-top would be again alive !
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;
}
Upvotes: 0