Bipin Bhandari
Bipin Bhandari

Reputation: 2692

unexpected behavior of margin-top css property

I am facing very simple problem with margin-top and its freaking me out. I have simplified my document to make it readable. Here is my structure of html document

<body>
    <section>

    </section>

    <section>
        <div></div>
    </section>
</body>

Here is my CSS

section{
    width: 100%;
    height:768px;
    background-color: red;
    border-bottom: 1px solid yellow;
    position: relative;
}

div{
    background-color:green;
    height:50px;
    width:50px;

    margin-top:0px;
}

When div's margin-top is 0, it looks like this: enter image description here

But when I change it to margin-top to 10px, it looks like this:enter image description here

I could not point out how that white space is added. Inspection shows that it is the part of body. Section is actually pushed down. I was expecting that small div to be pushed down relative to section. Can anyone explain this weired behavior?

Upvotes: 1

Views: 134

Answers (3)

h0mayun
h0mayun

Reputation: 3621

try

float: left;

for section tag if you can

http://jsfiddle.net/dcTw3/2/

Upvotes: 0

fidel castro
fidel castro

Reputation: 1607

here the fiddle http://jsfiddle.net/suriyag/UhqX9/1/ that has solution for your requirements

    section{
    position:relative;
    width: 100%;
    height:768px;
    background-color: red;
    border-bottom: 1px solid yellow;
    position: relative;
}

div{
    position:absolute; 
    top:10px;
    background-color:green;
    height:50px;
    width:50px;
  }

did some little changes in your code

Upvotes: 1

Ali Bassam
Ali Bassam

Reputation: 9969

From w3.org:

In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.

Now to prevent collapsed margin, you should add overflow:auto to the parent element.

Upvotes: 0

Related Questions