views:

134

answers:

4

I am trying to get rid of this:

document.body.className = "someclass";

I want to do this in CSS.

body.someclass {
.
.
.
}

unfortunately I am not able to get this working in Firefox, chrome.

Am I doing anything wrong here? Is there any way we could apply a CSS class to body?

+9  A: 

You are doing two different things there. Your JavaScript is actually assigning the class "someclass" to your body element, while your CSS is styling a body element with the class "someclass", it won't assign the class to it, that is not the task of CSS. You would do it in plain (X)HTML like this:

<body class="someclass">
dominikh
i've used this before and it works. +1
pixeltocode
Thanks for that, I was able to apply by this way.
Manohar
+2  A: 

Part of the problem is that valid XHTML can only have one <body> element per document. A class is generally ascribed to an element that occurs multiple times (or, rather, to a style that you want applied multiple times).

SINCE there's only ever one body, I've never added an ID or a class to it. Just style:

body {
    background-color: red;
}

If you have a class you want to reuse, use a comma in your selector:

.coolStyle, body {
    font-weight: bold;
    color: red;
    text-decoration: blink;
}

All of this is potentially meaningless, however, because anything applied to the <body> tag will be inherited by its children unless explicitly styled otherwise.

Alex Mcp
Maybe he is later changing the class using JavaScript and just wants to provide a default in a verbose manner? of course I am just making assumptions there.
dominikh
I think it's important to note that there's only one body tag, but if you link to an external css file then that file could potentially encounter several different web pages that need the body tag styled differently. It's also kind of moot if you use the document level css styling in the header instead of adding classes for body tags in the external css file.
Nitrodist
A: 

There is no need for a class on body since you will only have one body in your document. Unless maybe you want to change the style of the body by changing with JavaScript class for some reason.

If you have to put a class on body do it like this:

<body class="someclass">

And then access the class and modify the style in your css like this:

body.someclass{
  ...(style parameters goes here)
}

However you can change the style of all elements of a tag and since you will only have one body you could simply add this to the css:

body{
  ...(style parameters)
}

And not add anything to the html. However with reoccuring tags do use class for a style that will be used several times and id for a style that will only be used one time on a page. You assign an id to a tag like this in the html:

<tag id="someid">
Hultner