Why should I use a container div in HTML?

Viewed 161083

I have noticed a common technique is to place a generic container div in the root of the body tag:

<html>
  <head>
    ...
  </head>
  <body>
    <div id="container">
      ...
    </div>
  </body>
</html>

Is there a valid reason for doing this? Why can't the CSS just reference the body tag?

11 Answers

The container div, and sometimes content div, are almost always used to allow for more sophisticated CSS styling. The body tag is special in some ways. Browsers don't treat it like a normal div; its position and dimensions are tied to the browser window.

But a container div is just a div and you can style it with margins and borders. You can give it a fixed width, and you can center it with margin-left: auto; margin-right: auto.

Plus, content, like a copyright notice for example, can go on the outside of the container div, but it can't go on the outside of the body, allowing for content on the outside of a border.

This method allows you to have more flexibility of styling your entire content. Effectively creating two containers that you can style. The HTML body tag which serves as your background, and the div with an id of the container which contains your content.

This then allows you to position your content within the page, while styling a background or other effects without issue. Think of it as a "Frame" for the content.

The most common reasons for me are so that:

  1. The layout can have a fixed width (yes, I know, I do a lot of work for designers who love fixed widths), and
  2. So the layout can be centered by applying text-align: center to the body and then margin: auto to the left and right of the container div.

I've never heard of issues using a div class="container" markup. But I have heard of issues using body as a top level container. See this article. Stick with the tried and true; who knows what browsers will do in the future.

Forget the container. It's just a habit from the old, very old days.

Everything you can do using a div—you can also do it on a body tag.

Related