开发者

Is not changing the body an HTML/CSS standard?

Often times I see something like this:

<body>
  <div class="container"&开发者_如何学编程gt;
  </div>
</body>

Why not just do:

<body class="container">
</body>


You are perfectly free to do any of the following:

  • add a class or id attribute to the body element;
  • directly apply CSS to the body element, with or without class or id attributes; or
  • directly apply CSS to the html element, although without the class or id attributes and with some important caveats.

Any of these are perfectly legitimate uses of CSS and HTML.

Why <div id="container"/>? Through the years, many CSS techniques have employed arbitrary container elements for conceptual simplicity, to avoid certain cross-browser inconsistencies or because they were simply too complex to be achieved otherwise. A couple of more subtle reasons include that in older browsers, one could not apply CSS to the html element directly, and there were (and are) certain unusual or restricted properties for those elements—often for obvious reasons. (They were sometimes described as being "magic" for this reason.)

These all conspired to create a situation where to achieve almost any moderately complex layout, it was inevitably much easier to just start out with a squeaky-clean container element. Though the practice started as a means to an end it soon became just part of the scenery, and now many developers don't think twice about adding that sprinkling of extra markup.


No, there is nothing that says you can't add a class to the body.

Attaching a class to the body is actually quite common in various CMSes and is very handy for theming or styling specific pages.

From looking at your example, if you just want to use the body as a container, why even bother with the class? There should only be one body element, so just call that in your selector.


Walter, it may make sense if you needed to apply a slightly different subset of styling to a page with a custom body tag.

Using a wrapping div is usually for some presentational reason and make not make sense semantically; if you don't need it for your project, don't use it. Sometimes only using the body tag to contain the page is too inflexible for some layouts, and as Jordan says some old browsers cannot apply CSS to the root element.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜