Styling the html and body Elements
One of the most common ways to begin a layout in HTML is this:
<html>
<head>...</head>
<body>
<div id="wrapper">
<div id="container">
...
</div>
</div>
</body>
</html>
That’s the ol’ double-wrapped div
layout technique. But, since we already have the html
and body
elements, the div
elements might be redundant in a lot of situations. So in order find out if CSS styles can be applied to the html
and body
elements just like our hard-working wrappers, I tested a range of CSS properties in FireFox 3, Safari 3.2, Opera 9.6, and Internet Explorer 6, 7, and 8. Here’s what I found.
You can add padding to the html
and body
elements and it works in all browsers tested. However, borders are a different story. While you can add a border to the html
element in all browsers tested, IE6 and 7 only allow a solid border. Also, IE6 extends the border around the whole viewport, regardless of how much content is visible, even to the right hand side of the scroll bar.
Adding a margin to the html
element works in all browsers tested except IE6, which ignores it. A background color on either the html
or body
elements will cover the whole viewport, regardless of margins.
One quirk I found was that if you have a background image on the html
element as well as a top margin, Safari and IE7 will ignore the margin and display the background starting from the top left corner of the viewport. Firefox Opera and IE8 will display the background image inside the margin area just like normal elements. All browsers respect margins on the body
element and place background images correctly.
If you try some crazy CSS like absolutely positioning the html
element, you’ll find it actually works in Opera, and IE7 and 8. However, Firefox and IE6 will ignore it, and Safari will be extremely confused and display a broken mess.
So what does work? Adding a background image to the html
and body
elements works fine, and you can use it in place of multiple background images that only Safari currently supports. One of the solutions in the SitePoint book, The CSS Anthology uses this technique.
You’ll be happy to note that centering a single fixed width column is a snap:
html {
background-color: #333;
}
body {
background-color: #fff;
width: 750px;
margin: 0 auto;
}
The above code will work flawlessly in all the tested browsers.
There’s one big gotcha though: if you need to use absolute or relative positioning for elements inside the body
element. I’d assumed that since all elements obtain a positioning context from the body
element by default, if I centered the body
element the default positioning context should adjust accordingly. I was wrong! The default positioning context remains fixed to the viewport; you have to add position:relative;
to the body
style to create a new positioning context:
body {
position: relative;
background-color: #fff;
width: 750px;
margin: 0 auto;
}
Refreshingly, that’s consistent across all tested browsers.