Navneet Saini
Navneet Saini

Reputation: 944

Why isn't 'margin-top' property working?

I am aware about the concept of 'margin-collapse'. But , why am I not able to see 10 px margin on the top of the first box here. The top box(which has the id 'first') should have 10px margin above it. If this is not the correct wat to get it, then what is it? And, why this doesn't work.

CSS:

#Main{
background-color: gray;
position: relative;
width: 200px;
height: 300px;  
}


.box{
position:relative;
height: 60px;
width: 175px;
background: black;
margin: 10px 10px 10px 10px;
}

HTML:

<div id="Main"> 
    <div id="first" class="box"></div>
    <div id="second" class="box"></div>
    <div id="third" class="box"></div>
</div>

I know one way could be that we can give 10px padding to the parent div. But then why doesn't this thing work?

Upvotes: 0

Views: 1612

Answers (2)

Kevin Lynch
Kevin Lynch

Reputation: 24723

This is how browsers interperit the code. It does not output the expected result which would be a 10px gap between the top of the child and the outter parent. You could add padding-top to the parent, alternatively you could assign overflow:auto; to your main div.

DEMO http://jsfiddle.net/kevinPHPkevin/2f4Kz/4/

#Main {
    background-color: gray;
    position: relative;
    width: 200px;
    height: 300px;
    overflow:auto;
}

Another way around this is to add a transparent border around the main div (stops margin collapsing)

#Main {
        background-color: gray;
        position: relative;
        width: 200px;
        height: 300px;
        border: thin solid transparent;
    }

The third a final option (to my knowledge) is to stop the margin collapsing by setting padding-top: 1px; margin-top: -1px; to the parent div

#Main {
    background-color: gray;
    position: relative;
    width: 200px;
    height: 300px;
    padding-top: 1px;
    margin-top: -1px;
}

Upvotes: 1

Surfine
Surfine

Reputation: 392

The margin: 10px 10px 10px 10px in your code moves the "Main" box as well.
If you want to move the box with id "first" only, use position:relative; top: 10px;
jsfiddle demo

edit: I don't know to say for sure why this happens but my guess is it is because the display of the "Main" box is block by default.
When you use display: inline-block; on the "Main" box, the problem is fixed. (jsfiddle)

Upvotes: 2

Related Questions