LastSecondsToLive
LastSecondsToLive

Reputation: 744

Why should I use a class or an id on a <body> tag?

I see a lot of people giving the HTML <body>-tag an id or a class to access it via CSS. Why would I do this, when I am able to access it directly as tag itself?

Why would I do this?

Example 1:

.body-wrapper {
   margin: 0px 3px;
}

Instead of this?

Example 2:

body {
   margin: 0px 3px;
}

Upvotes: 4

Views: 2859

Answers (2)

Michael Benjamin
Michael Benjamin

Reputation: 372059

Consider these two scenarios:

  • You have anchor elements throughout your page. Each of these anchor elements takes the user to the top of the page, like so:

    <a href="#top-of-page">Go to top</a>
    

    Well, the top of the page could be this: <body id="top-of-page">

  • What if you want certain elements to have similar styling, such as a border.

    .frame-this { border: 2px dashed black; }
    

    If you want the body element to have this border, it would take this class:

     <body class="frame-this"> ... </body>
    

These are somewhat far-fetched scenarios, but they illustrate two reasons where the body element might need an id or a class.

See also this article on CSS-Tricks: Why use Classes or IDs on the HTML element?

Upvotes: 3

Hatchet
Hatchet

Reputation: 5428

It's useful if you want to have as few stylesheets as possible (like, say, one), but still want to customize the display of certain pages.

This can be useful:

  • If you want to change the background for one of your webpages.
  • If you want to dynamically change the theme of your site (like http://lisperator.net/ does, though it's on the <html> tag)
  • Do something nifty with JavaScript to transform the webpage (see previous list item)
  • It's CSS. You can do what you want with it!

More about this on CSS Tricks.


Press Ctrl+U.

Press Ctrl+F. Type <body.

Wonder of wonders! StackOverflow uses <body> classes!

NOTE: SO doesn't style them directly with CSS, but rather uses them as handles for JS

Upvotes: 3

Related Questions