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?

有帮助吗?

解决方案

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.

其他提示

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 .

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top