View Full Version : Classes v ID

06-27-2005, 10:09 AM
I've been browsing through the posts on this forum and notice that most people seem to use IDs when declaring CSS settings. I've tended to use Classes all the time but now I'm wondering if I'm missing something.

What's the difference and what's the pros/cons of each method?

By the way, can anyone reccomend a good, comprehensive reference book on CSS?

06-27-2005, 10:27 AM
Classes can refer to many elements, ids are supposed to refer to only one element per page but, since browsers ignore this in many situations, lots of folks prefer ids as they require less typing when inserting them as attributes. There may be a host other differences but, that's the only difference, other than the way they are written in the stylesheet*, that I know of. You can get into real trouble using javascript to access an element by id if more than one element on the page has said id.



06-27-2005, 12:49 PM
Classes can refer to many elementsThat's the main usage difference. If you only have one element, and there will only ever be one element, that requires a certain style then use an id selector. If more than one such element exists, then use a class selector.

ids are supposed to refer to only one element per page but, since browsers ignore this in many situationsBrowsers have to put up with many authoring mistakes to make sure that their users don't accuse them of being broken. That's part of the reason that Mozilla has an evangalism project - to try and get authors to write HTML and CSS properly so it's not necessary to 'break' browser functionality to get the intended layout.

A behavioural difference between class and id selectors is that which surrounds specificity and the cascade. As an id selector refers to just one particular element, it is considered very specific and so the declarations for that rule will override declarations from other rules. Similarly, class (and pseudo-class) selectors typically identify particular 'types' of element, so they are more specific than element (and pseudo-element) selectors alone.

So, from most specific, to least:

Inline style rules (style attributes in HTML).
An id selector (#identifier).
A class (.class), pseudo-class (:hover, for example) or attribute ([attr...]) selector.
An element or pseudo-element (:first-line, for example) selector.
Universal selector (*).


06-29-2005, 09:14 AM
I like Id, combine with javascript getElementById(":)")