View Full Version : Parent div moves when i change child div's margins ?

Nov 14th, 2009, 09:09 PM
i have a <div> inside another <div>

I want the parent div to stay exactly where it is, and the child div to be inside it but with a 20px margin from the top.

But when I add the 20px margin, the parent div moves downwards by 20px so the child div is still at the very top edge.

Example of what is happening is here: http://www.eionbryant.com/test.html

I want the green area "#wrap" to be flush with the purple strip... and the grey area "#boxes" to begin inside the green area 20px down.

I am learning css, so i would prefer someone explained how I am doing it wrong, rather than offering some work around.



<div id="strip"> </div>

<div id="wrap">

<div id="boxes"> </div>




body {background:#FFFFF; font-family:"Trebuchet MS", Times, serif; padding:0; margin:0; position:relative; }

#strip {background:#663366; width:100%; height:10px; padding:0; border:0;}

#wrap {background:#00FFCC; width:100%; height:700px; margin:0 auto; }

#boxes {background:#666666; margin: 20px auto; width:800px; height:200px; clear:both;}

Nov 14th, 2009, 09:42 PM
You aren't doing anything wrong. That's just how it works in that instance. It has to do with how margins collapse when there's one on top of the other and it affects child elements also.

The way around it is to add a border to "wrap" of, say, 1px and make it the same as the background color or transparent.

Nov 14th, 2009, 09:47 PM
Wow, Thanks.

The way that positioned css is formatted by a browser seems very strange and illogical to me..Like do I always need to add a border for Div to stay positioned?.. is there somewhere that has some good info that I can read to get my head around such things?

Nov 14th, 2009, 10:44 PM
As explained above you are experiencing collapsing margins (http://reference.sitepoint.com/css/collapsingmargins), which is default behaviour.

There are many triggers to prevent collapsing margins, borders being one of them, but the most commonly used one is to add:


to the parent DIV

Nov 15th, 2009, 11:36 AM
Or you may set a padding-top on the container instead of margin-top on the child.