Thursday, July 19, 2007

Firefox window top margin "bug?"

Sometimes Firefox may render additional margin at the top of the window even though all margins of top-level boxes and html/body container are set to zero. For example:

<html>
<head>
<title>FireFox Top Margin "Bug?"</title>
<style type="text/css">

html, body {
margin: 0px;
padding: 0px;
border: 0px;

font-family:sans-serif, Tahoma, Arial, Helvetica;
font-size: 10pt;
background-color: #ffffff;
}

#maincontents {
margin: 0px;
padding: 0px;
border: 0px;

height:100%;

background:#bbeebb;
}
</style>
</head>

<body>
<div id="maincontents">
<p>filler</p>
<p>filler</p>
<p>filler</p>
<p>filler</p>
<p>filler</p>
<p>filler</p>
<p>filler</p>
<p>filler</p>
<p>filler</p>
<p>filler</p>
</div>
</body>
</html>


The strange thing is that margin disappears if you set border and make it visible, i.e. add border:1px solid to #maincontents style.

While it looks like a bug this case is actually covered in specification. In particular it is said that adjoining margins are those of boxes not separated by padding or border areas. It is also said that these are collapsed to form a single margin for unlimited number of nested boxes. The margin height is equal to maximum margin from the set of boxes.

So if you do not want any margins like that - and top window margin is just the specific case of it - you may try to make troublesome box floated or teach children how to behave properly.

#maincontents {
margin: 0px;
padding: 0px;
border: 0px;

height:100%;

background:#bbeebb;
}

#maincontents > :first-child {
margin-top:0px;
}

See example files at: http://rainforce.org/pile/css/

2 comments:

  1. Thank you! I have been struggling with why firefox kept adding all this extra space to the top. In end, this fix made it look nice like in Chrome:
    body {
    border-top: 1px solid transparent; /* FF fix */
    }
    #page {
    border-top: 1px solid transparent; /* FF fix */
    }

    Thanks for the idea to use the border.

    ><> Brian

    ReplyDelete
  2. No problem. For consistency of default rendering between browsers you may take a look at reset.css - http://meyerweb.com/eric/tools/css/reset/

    ReplyDelete