When I started using CSS about 140 moons ago, the way that I remembered the difference between an ID and a Class was as
ID = A student's Identification is unique to one student
Class = There are many students in a class.
w3.org states the following:
id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.
class = cdata-list [CS]
This attribute assigns a class name or set of class names to an element. Any number of elements may be assigned the same class name or names. Multiple class names must be separated by white space characters.
The id attribute assigns a unique identifier to an element (which may be verified by an SGML parser). For example, the following paragraphs are distinguished by their id values:
<P id="myparagraph"> This is a uniquely named paragraph.</P>
<P id="yourparagraph"> This is also a uniquely named paragraph.</P>
The id attribute has several roles in HTML:
- As a style sheet selector.
- As a target anchor for hypertext links.
- As a means to reference a particular element from a script.
- As the name of a declared OBJECT element.
- For general purpose processing by user agents (e.g. for identifying fields when extracting data from HTML pages into a database, translating HTML documents into other formats, etc.).
The class attribute, on the other hand, assigns one or more class names to an element; the element may be said to belong to these classes. A class name may be shared by several element instances. The class attribute has several roles in HTML:
- As a style sheet selector (when an author wishes to assign style information to a set of elements).
- For general purpose processing by user agents.
Nowhere does it state that a class attribute cannot be unique, this would depend on the website developer on how he/she implements the class. ID does have a limitation in that it must be unique.
This means that we have a choice when using an attribute where it is used just the once in a document, class or ID.
Logic now says that we should not be using the ID attribute as a style sheet selector, a class attribute does this just as efficiently as an ID. OK I hear you saying ‘what if the element with the ID needs styling?’. In this case there is nothing wrong with applying a class attribute for styling purposes as in <div id=”John” class=”Maths”>.
Please give me feedback on this topic and tell me that I am wrong. Otherwise I will start boycotting the ID attribute from my style sheets. In fact I would love to see w3.org adjust the roles for an ID to exclude the style sheet selector bit.