tags:

views:

421

answers:

4

I have a problem with a following sample html/css code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"&gt;
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sample</title>
<style type="text/css">
* { padding: 0; margin: 0; border: none; outline: none; }

#container {
margin: 10px auto 10px auto;
width: 960px;
background-color: #dddddd;
border: solid 1px black;
}

#container2 {
margin-left: 200px;
margin-top: 400px;
background-color: yellow;
}

</style></head>
<body>
<div id="container">
<div id="container2">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
</div>
</body>
</html>

The sample page looks as I expect, i.e. the lower div (yellow) is pushed 400px down from the top border of the outer div (gray).
But, when you remove line: border: solid 1px black; from the style definition of #container, the outer div (gray) starts from the same top position as the inner div (yellow).
This happens in Firefox 3.x and Chrome.
Can someone explain why does it happen ? In my opinion, removing border style should not affect this layout at all.

A: 

The width of the border takes space, which can cause layout changes to happen. In order to account for that, you might need to change your margins/padding by the width of the border.

Alan Jackson
i thought that was the problem too, but after looking at what's happening this is not the case, the two pages look completely different.
John Boker
A: 

If you add

float: left;

on your #container div, then the grey box will have the same height as before you removed the "border" from your style.

Then you just need to position the box the correct place.

Hope this helps out...

Kim Andersen
+4  A: 

Borders separate collapsing margins: http://www.w3.org/TR/CSS21/box.html#collapsing-margins

David Dorward
Thanks for providing the clue. I have added `<br clear="both"` after the `<div id="container">` and now it works as it should be.
Wacek
+2  A: 

Really weird. If you want to do away with the border, add a padding: 1px to #container, and you can remove the border without affecting the layout.

jeffreyveon
I am intrigued. Is this the "correct" fix? Why does this work?
DanDan
This fix works. However, it's rather a workaround than a solution. The proper solution is to add `<br clear="both">` to the `#container` div. According to CSS, when there is a clearance, then vertical margins do not collapse. Thanks anyway.
Wacek