I’ve recently been teaching myself HTML5 and CSS3. It’s actually pretty sweet – all of the new things that have come out for both areas. But while going over CSS I realized I didn’t really understand something – what is the difference between an ID and a Class in CSS?
For a while there I figured they were pretty much interchangeable, but that thought didn’t quite sit right with me. If and ID and Class are interchangeable then why have both available if they do the same thing in the CSS code? Well after coming to a decent stopping point in my book, I did what I usually do when I don’t know something – look it up on Google.
To my surprise I actually found the answer on page 1 and within the first 10 available links. (For once I didn’t have to search through the massive haystack that is Google for that 1 needle of an answer.) And here’s what I found out:
IDs and Classes are set up basically the same way in an HTML or CSS document, with the major differences showing up in the coding style used in CSS.
For IDs:
HTML setup
<p id = “idexample”>This paragraph shows the CSS style for an ID.</p>
CSS Setup
P#idexample
{ backgroundcolor: white; }
For a Class:
HTML setup
<p class = “highlight”>This paragraph is highlighted using the CSS style for a class.</p>
CSS Setup
p.highlight
{ color: green; font-weight: bold}
Nothing new here, right? Well the main difference aside from the CSs formatting is the usage of each. Basically you use an ID when you want something formatted as certain way ONLY ONCE on the page. So if you want a heading green, bold, uppercase and italicized only once, use an ID. (Best comparison – you are a single person with 1 ID card.)
A class is used when you want something formatted throughout the page more than once. Best place I can think to use a class would be to format the text in several paragraphs. (Best comparison – there are many people in a classroom.)
Usually you want to use an ID once on a page since they are considered unique. This doesn’t mean you only use an ID once ever on a page, but you use the name you set an ID to once. So, id=”heading1”, id=”paragraph heading”, id=”sentence style”, etc.
The next question I had was what happens if the IDs and Classes end up conflicting with each other for some weird reason. (I go code crazy sometimes so this happens to me on occasion.) The answer to this is an ID holds hierarchy over a Class, so an ID would be used. It’s like the same method used when you have inline CSS code and a linked style sheet for the same HTML document.
So basically, use an ID for one occurrence and a class for several occurrences.
http://www.tizag.com/cssT/cssid.php
http://css.maxdesign.com.au/selectutorial/advanced_idclass.htm

