Difference between ID and Class – CSS

Yesterday one of my colleagues(a fresher) asked me difference between ID and class – CSS selectors. I explained him basic difference but he was still curious so I googled a bit about this. Believe me, I didn’t know all the differences between ID and Class. So I tried to sum up the difference between CSS ID and Class. I hope these will be helpful to you.

  1. Id begin with “#” and Class begin with “.”
    For example ID is #newID
    Class is .newClass
  2. ID is unique but Class is not
    This is known to most of as a hard coded rule but few of us know the exact meaning of this. It simply implies that in case of ID ‘Each element can have only one ID’ and ‘Each page can have only one element with that ID’ where in case of Class ‘You can use the same class on multiple elements’ and ‘You can use multiple classes on the same element’.
    For example ID < div ID=”newID”> </div>
    Class < div ID=”newClass”> </div>
    < div ID=”newClass”> </div>
    < div ID=”newClass”> </div>
  3. Browsers are equally compatible with ID and Class
    At times, we have a project working perfectly OK by using IDs where as same functionality don’t works on some other project where we used classes. As a fresher, my first thought on these scenarios was that class is causing problem and I would convert all the classes to ID. But, over the years, I learned that replacing ID with class(and vice versa) don’t helps, provided you were earlier using these correctly.
  4.  An element can have both: ID and Class
    An element can have both ID and Class but ID have higher preference over class.
    For example < div class=”redBackgroundColor” id=”grayBackgroundColor”> </div>
    In this case the background color of div will be gray

A commonly asked question is ‘What if I used an ID twice on a page. Will application crash or something’. The answer is that the application don’t behaves abnormally but it won’t pass the CSS Validation which is a must for all the websites for good ranking on search engines
Also if we have to use JavaScript for any element, then we have to enforce unique ID for element otherwise typescript won’t work as JavaScript methods(e.g. getElementById) won’t be picking up the correct element.

Now the real question, Should one use ID or Class ? . The answer to this question is simple, for the information that will be reused on should use class and for the information that is unique(and will not be reused) use an ID
For example, class should be used for tablerows, table cells etc. ID should be used for header, footer etc and for elements that are to be accessed in JavaScript.