tags:

views:

70

answers:

3

Here's the problem :

I have 2 div - The first one has a float:left - The second one has a margin-top

Now why, WHY does that margin-top is also applied to the first div ?

Here's a demo with background colors to get the idea :

http://dl.dropbox.com/u/4225936/whyyyyy.htm

-Edit : I'm not looking for a solution but for an explanation of this behavior. Thanks everybody :)

+1  A: 

give float:left; for the second div also

<div style="background: none repeat scroll 0% 0% red; margin: 0pt;">
<div style="background: none repeat scroll 0% 0% green; float: left;">hello</div>
<div style="background: none repeat scroll 0% 0% gold; margin-top: 50px; float: left;">hello</div>

here the result.

Sotiris
Hi, thanks for giving a solution and taking the time to create a demo, but as I said to Webarto I'm not looking for a solution but for an explanation of this behavior. I should have told that from the beginning sorry.Still +1 for the demo :)
Daniel
probably this happens because the container div (the red) hasn't any height,padding or margin. So there is no fixed position to begin. If you set any of the above on the red div, the second div will start the margin from the top of it, instead of body (as it does now)
Sotiris
A: 

You can use padding-top instead of margin-top

Webarto
I already found different ways to solve the problem, but I would like to know why is this happening...But still, thanks.
Daniel
I suppose he wish to move the div, not the content. If he uses background (like his example), then the color will fill and the padding area.
Sotiris
+3  A: 

You're running into something called margin-collapse.

If two margins are adjacent, the larger one will take precedence. Since the margin on your second div is adjacent to the margin on your container div, those margins collapse, and the larger one (50px) takes precedence, and affects them both.

If you add a top padding to the container, the effect will be removed because the margins are no longer adjacent.

Edit: Note that "larger" is sometimes not exactly right. A negative margin takes precedence over a zero margin, for instance. I haven't tested exactly what the calculation is, so take "larger" with a grain of salt.

Ryan Kinal
Thanks a lot Ryan, you just gave me my sanity back :-)
Daniel
Always glad to help!
Ryan Kinal