Class or ID on Body Tag

Jo Sprague picture Jo Sprague · Oct 13, 2010 · Viewed 59.1k times · Source

I've been applying an ID to the body tag of my HTML documents lately to allow greater CSS control (#9). Recently the though occurred to me that I could do exactly the same thing by applying a class to the body tag. I want to know positives and negatives of each choice. If I have multiple pages where the body tag has the same ID, is it better to use a class? What do you think? Why?

UPDATE: The class/ID is basically what I intend to use to identify to the stylesheet which page or type of page the stylesheet is being applied to. For example, is it the homepage, the contact page, one of many search results pages, an archive page, etc?

Answer

Dagg Nabbit picture Dagg Nabbit · Oct 13, 2010

Using a class is perfectly acceptable, possibly more so than using an id. Use of ids should be limited as much as possible, because they can clash with other ids and break things like document.getElementById.

An id selector is more specific than a class selector, which usually makes it a better choice for your use case. -- David Dorward

However, a high "specificness" is not always desirable. Consider body#faq #col_b a {color:gray;} in master stylesheet and then someone develops a plugin with a gray background that goes on faq page, now they need to use !important or create another id attribute to give higher specificity.

Also, consider the use of multiple classes in a single body element:

<body class="faq two_column big_footer"> ...