Classes or IDs

It is often asked (I think often) in CSS discussions, “What really is the difference between class and ID?”

The traditional answer I learned in school: A class is for selecting a bunch of elements on a page; an ID is for selecting one item and possibly writing a script for it. You can have many classes, but only on instance of an ID on a page.

Okay, that is clearly not the full answer, so here’s what I came up with in the bathroom this morning.

An ID specifies one single element. An <a> with an ID of Jeremy gives that anchor a name of “Jeremy” and then any time I refer to #Jeremy, I know I’m only referring to <a id="Jeremy">.

A class specifies a bunch of elements that have something in common and represent a subset of similar elements. For example, perhaps all anchors have an underline and are the same weight as the surrounding text simply because they are anchors and that’s what they do by nature. If I define <a class="Jeremy">, I’ve created an entire new subset of anchors that can have any new styles I wish to apply while still retaining any characteristic of being an anchor that I don’t explicitly override. The CSS code a.Jeremy {font-weight: bold;} would cause my subset of anchors to show up as bold while still retaining any other style inherited from simply being an anchor. So, really, a class creates a new type of element. We started with a and we now also have a.Jeremy.

The difference between class and ID is definitely more than “one is for single elements and the other is for many”.

Leave a Reply

Your email address will not be published. Required fields are marked *