Interview Questions

What's the difference between 'class' and 'id'?

CSS Interview Questions and Questions

(Continued from previous question...)

102. What's the difference between 'class' and 'id'?

As a person, you may have an ID card - a passport, a driving license or whatever - which identifies you as a unique individual. It's the same with CSS. If you want to apply style to one element use 'id' (e.g. <div id="myid">). In the stylesheet, you identify an 'id' with a '#' ie. '#myid'...
As a person, if you are in a class, you are one of many. It's the same with CSS. If you want to apply the same style to more than one element, use 'class' (e.g. <div class="myclass">). In the stylesheet, you identify a 'class' with a '.' ie. '.myclass'...
If id's are more restrictive than classes, then why not just litter your page with classes? Well, I think the main thing is that it's simply wrong. You don't put headings in 'p' tags - you use 'h1', 'h2', etc. You don't (or shouldn't) make a list by writing asterisks or the little divider bar ( | ) - you use list tags ('ol'/'ul' + 'li') . You don't say that your footer is part of a class of elements called 'footer' - that's just stupid - you can't have more than one footer - it can't be a class. Of course, practically, the effect is about the same - the rules are applied - but that's not the point - it's semantically wrong to do it that way... However, if you try to give more than one element the same id, you will have problems - so don't do it.
An element may have an id and a class, but that's usually not necessary. You can also give an element two classes if you need to - like this : class="class1 class2". It can be very useful. Needless to say, you can't give an element two id's.
Another difference is to do with power. You can give an element an id and a class, but if any of the properties of the two conflict, the id style will win. Ids are more powerful than classes.
One more useful thing about id's is that they can be used as a link reference. Many people still think that you need named anchors to make links within a page, but that's simply not true - in fact, the name attribute is deprecated in XHTML except for in forms. One example of using id's as link references is this page. There are no named anchors on this page - the questions at the top of the page link to the id's of the divs that the answers are in.

(Continued on next question...)

Other Interview Questions