Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply CSS to HTML body element?

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?

like image 846
Manohar Avatar asked Apr 06 '10 03:04

Manohar


People also ask

Can you put CSS in HTML body?

CSS can be added to HTML documents in 3 ways: Inline - by using the style attribute inside HTML elements. Internal - by using a <style> element in the <head> section.

How do I select a body in CSS?

Type Selectors correspond with HTML elements. ID Selectors are used by adding # in front of an elements ID. Class Selectors are used by adding a period in front of an elements class.

Can I use style inside body?

The <style> element must be included inside the <head> of the document. In general, it is better to put your styles in external stylesheets and apply them using <link> elements.


2 Answers

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">
like image 103
Dominik Honnef Avatar answered Sep 18 '22 14:09

Dominik Honnef


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.

like image 27
Alex Mcp Avatar answered Sep 17 '22 14:09

Alex Mcp