Joel
Joel

Reputation: 59

margin-top issue on HTML

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 ?

Upvotes: 2

Views: 245

Answers (5)

Karthi Keyan
Karthi Keyan

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

imbondbaby
imbondbaby

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

JSFiddle Demo

More info on collapsing margins can be found here.

Upvotes: 1

Hardy
Hardy

Reputation: 542

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

Upvotes: 1

DigitalDouble
DigitalDouble

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

divy3993
divy3993

Reputation: 5810

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;
}

Upvotes: 0

Related Questions