RK* - rikkertkoppes.com

thoughts

[HTML & CSS] about class, id and style

A common misconception is that the class attribute is meant to "define a style" for a group of elements. This is not true. It is also not true for the id attribute.

In fact, there is no specific attribute to "define a style". By specification, you can do this with any attribute. And shortcut selectors are made for commonly used attributes (the "." and "#" selector for class and id resp.). An element with a specific attribute can be selected with E[foo="warning"], although this does not work in IE (pretty strange don't you think?).

Then what are the id and class attributes for? Let's have a look what W3C has to say:

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.
W3C: Element identifiers: the id and class attributes

So what does this mean? An id is an identifier for an element, just like you have a social security number (SoFi number in the Netherlands). This identifier can be used as an end anchor for a link, it can also be used in Javascript when playing with the DOM tree (the function getElementById might ring a bell).

The class attribute is meant to define a class of elements, just like it says. For example when I use the <code> element in a document, I might want to specify what kind of code this element contains (HTML, CSS, Javascript or whatever), or in other words: to what class this code belongs. Classes are like occupations. Different people (different id's) might do the same job and therefore might look the same (police officers), which is defined by style.

Just as people might do two or more jobs, elements might belong to more classes. These classes appear as a space seperated list in the class attribute.

So, in practice, you "hook" the style to a specific attribute (mostly id or class) and not vice versa. Keep this in mind when defining classes. Classnames like "red_border" are not smart names for a class (just like the name of the job "police officer" is not "black uniform and hat"). Classnames should describe the function of a group of elements. It's more like an extension to the element's name.

Further reading

Additional resources (top 15)

Below is a list of additional resources that might contain extra information about the subject at hand. These are all sites linking to this one (i.e. backtracking).

  1. Particletree · A Guide to Unobtrusive Javascript Validation (249)
older articles

AdministrationAtom feed