View Full Version : margin-top of div doubles if adjacent parent div has no border

09-03-2010, 05:17 PM

I use several (in my example 2) div boxes with absolute width (200) on the left and a box with variable width (remaining space) on the right.
The boxes on the left are included in a container (divleft), the box on the right is included in divright.

In my example, the right container has a red border.
If I remove this border (i.e. change 1px to 0px), then "BOX1" has double its distance to the top of the page - which is 20 pixels (while "BOX RIGHT" is still 10 pixels from the top). If I change the margin of the class "box" from 10px to 5 px, then only "BOX RIGHT" is 5 pixels from the top, while "BOX1" is 10 pixels from the top.

Can somebody please explain this behavior to me?

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="0">
<style type="text/css">

* { margin:0px; padding:0px; }

#divleft { float:left; width:200px; border:0px solid red; } /* left container */
#divright { margin-left:200px; border:1px solid red; } /* right container */

.box { border-style:solid; border-color:gray; border-width:1px; margin:10px; padding:5px; } /* This margin is not always 10px */
.boxtitle { background-color:gray; color:white; font-weight:bold; margin:0px; padding:5px; }


<div id="divleft"> <!-- left container -->

<div class="box boxleft"> <!-- BOX1 -->
<p class="boxtitle">BOX1</p>



<div class="box boxleft"> <!-- BOX2 -->
<p class="boxtitle">BOX2</p>




<div id="divright"> <!-- right container -->

<div class="box boxright"> <!-- BOX RIGHT -->
<p class="boxtitle">BOX RIGHT</p>





09-04-2010, 09:15 AM
If you use firebug to inspect the body element, when there's no border, you'll notice that the entire body element is pushing 10px downwards. It's due to collapsing of margins.

Adding a border or overflow:auto/hidden; to the container would resolve it. Or you'd need to remove margin-top from .box and apply an equivalent padding-top to its parent element. Read http://complexspiral.com/publications/uncollapsing-margins/