tags:

views:

187

answers:

3

Hi,
I have a problem with the margin-top in a nested div,
when I try apply margin-top in a nested div the margin is applicated to parent div,
any idea ?

+1  A: 

This is how margins work.. the margin is the space between the next element with a margin / padding / similar. It is not necessarily defined as its parent element. Consult the spec.

Here are some things you can do as a workaround

Use Padding Instead

This just means instead of using margin-top: 10px; you use padding-top: 10px;. This is not suitable for every occasion.

Weird Hack I Discovered

I doubt I discovered this initially, but the other day I solved the problem like this. I had a <div id="header" /> that I wanted to give a top margin too, and its top margin was pushing the parent (body element) down as well. So I did this on the body element...

body {
    padding-top: 1px;
    margin-top: -1px;
}

This made my margin work. You can also try using a border, like border: 1px solid #ccc.

It would also be wise to leave a note in the CSS comments to explain why you have that peculiar pair of rules. I just added /* this is to stop collapsing margins */.

Further Reading

Check out these other questions on Stack Overflow

alex
A: 

I get the solution with overflow:auto in the parent div.

JuanPablo
+1  A: 

Margins will collapse by design. Add 1px of padding as well and it should work fine.

edl
thanks, now I understand.
JuanPablo