Question

I'm using margin: 0 auto; to center the contents of my pages. Recently I discovered that using an automatic margin on a body has the same visual effect as an automatic margin on a (wrapper) div.

<!DOCTYPE>
<html>
<head>
    <style>
        div#wrapper {
            margin: 0 auto;
            width: 60%;
        }
    </style>
</head>
<body>
    <div id="wrapper">
        <!-- Rest of page. -->
    </div>
</body>
</html>

Compared to;

<!DOCTYPE>
<html>
<head>
    <style>
        body {
            margin: 0 auto;
            width: 60%;
        }
    </style>
</head>
<body>
    <!-- Rest of page. -->
</body>
</html>

It seems better as it removes an (unneccesary) element. Are there any pitfalls that need to be considered when using this approach?

Was it helpful?

Solution

I don't recommend it. Setting margin on the body boxes you in needlessly, and you end up using negative margins and absolute positioning to break out.

Stick with your container (or wrapper) model - it's widely considered a best practice. Check the source for this and any other professionally designed site and you'll see the same.

OTHER TIPS

I use the auto margin on the body all the time. You just have to remember that if you want to set a background for the page, you have to set it to the html tag, as people often set the page background on the .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top