Class! What's in an ID?
A CSS rule of thumb
November 30, 2014
Before we start in on the difference between class and ID, we ought to establish some similarities between the two. They are both used in the service of style. Instead of having to rely on only HTML elements and attributes, we can spell out the extras in a CSS (Cascading Style Sheets) file that can be used by more than one file across a site. There are no browser defaults for either ID's or classes declared in HTML pages. They both require an entry in the referenced CSS file to do anything at all. Once referenced, other sites can also apply the style-file by linking to the CSS page.
A good rule of thumb for describing the major difference between ID's and classes is that you should use an ID only once but you can use classes over and over. An element can have only one ID and each ID can have only one element. ID is starting to sound like a special case. In fact, this uniqueness allows a browser to get to an ID on a page by using a hash value like so: http://yourchickencoop.com#newsflash. This will also be more useful to the Javascript getElementbyID function.
Classes can be used over and over for different elements. Want the same font in links and paragraphs? Declare the #read-all-about-it class with a font and color. Then reference the same class in multiple elements. To change the font and color for Halloween, you only have to change it in one place..the #read-all-about-it entry in the CSS file.
a href class = "read-all-about-it"
p class = "read-all-about-it"
You can also apply different classes to the same element. For example, you could apply the class of box to get the basic shape of the thing (div class = "box"). To make the same box but in a different color specify two classes. (div class = "red box") This is an excellent way to get to a DRY (don't repeat yourself) web-site since all boxes inherit the same characterics. To override the shape of the box, we could specify an ID for a special case. In other words, we aren't boxed into a corner when declaring the class.


