View Full Version : Classes v ID
06-27-2005, 11: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, 11:27 AM
06-27-2005, 01: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, 10:14 AM
Powered by vBulletin® Version 4.2.2 Copyright © 2014 vBulletin Solutions, Inc. All rights reserved.