The Document
body
The body element acts as a container for all of the page’s contents, and that’s pretty much all it does.
Everything that’s displayed by the browser and seen by the user is wrapped in a single body element (and
only one body element is allowed per document). Its primary purpose is to separate regular content from
the metadata in the head element.
As with the head element, you can omit the start and end tags for the body element in some cases and the
element is still implied to exist. The browser will generate a body element even if the tags are missing, but
you can avoid potential problems by including the start and end tags yourself, just to be safe and keep
things tidy. Any content that appears outside the body element—actual or implied—could make the
document invalid, and that content might not be displayed.
There aren’t any required attributes for the body element, nor any special optional attributes, but it can
carry the usual global attributes that apply to almost every other element. It can be especially useful to add
an id or class attribute to identify the specific page, or classify general types of pages. Listing 3-7 shows
a body element with the ID “home” and the class “landing”, indicating that this is a landing-type page and
that it’s the home page, specifically.
Listing 3-7. The body element, identified and classified
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Power Outfitters Superhero Costume and Supply Co.</title>
</head>
<body id="home" class="landing">
<h1>Welcome, Heroes!</h1>
<p>Power Outfitters offers top of the line merchandise at
rock-bottom prices for the discerning costumed crime-fighter.</p>
</body>
</html>
With these attributes in place on the body element, they can act as handy “hooks” from which to hang CSS
rules, differentiating common types of pages or specific, unique pages. Listing 3-8 shows a few style rules
for level one headings, the h1 element. The first rule applies to all h1 elements, the second to h1 elements
on landing pages (any pages with the “landing” class), and the third is specific to h1 elements on the home
page (with the ID “home”). Because every element on the page descends from the body element, these
rules with their descendant selectors will be in effect no matter where the h1 might occur in the document
or what other elements might surround it—unless they’re overridden by another style rule, of course.
Listing 3-8. Using body attributes as style hooks in descendant selectors
h1 {
font-size: 20px;
}
.landing h1 {
font-size: 26px;