Forum Moderators: not2easy
My question: What is happening and how do I write correct code for this?
CSS:
#imgcontainer {
background-image:url('special_bg.jpg');
background-repeat:no-repeat;
width:420px;
height:220px;
margin:0px;
padding:0px;
background-color:#FF0000;
}
HTML:
<html>
<body>
<div id="imgcontainer">
<div style="margin:20px; padding:0px; width:260px;">
Some text
</div>
</div>
</body>
</html>
Thanks!
/Martin
<div style="margin:20px; padding:0px; width:260px;">
This is called collapsing margins [w3.org]. The 20px top padding on the interior div is collapsing with the 0 top margin on it's parent and creating the space you describe. The presence of padding or borders on the parent stops the collapse.
The best solution is to switch from using a top margin to using a top padding on the interior div. This is, after all, what you're actually after. You want space between the parent container's top edge and the child's top edge. Such a space is not technically defined by margin, which defines the space between two elements, but padding, which defines the space between an element's border and the stuff nested inside it.
Other options would include giving the parent element an overflow value other than "visible" (I believe auto works, but I'm not sure). Also floating or positioning the box would prvent it's margins from collapsing, but none of these are always posible within the layout. Switching to padding is really the best choice.
cEM