I just got an e-mail from a student last semester who was confused with the difference between when to use ID and when to use CLASS in CSS. I gave the standard explanation that ID is used in a single event while CLASS is used when there will be multiple occurrences.
So...
ID starts with a #
#singleOccurrence
{
font-family: arial;
font-size: 9pt;
}
Notice it uses the attribute ID in the tag.
<p id="singleOccurrence">This element will be used only once
CLASS starts with a .
.multipleOccurrences
{
font-family: arial;
font-size: 12pt;
}
Notice it uses the attribute CLASS in the tag.
<p class="multipleOccurrences">This element will be used more than once
The next question he asked was, "why can't I just use everything as classes, whether it be a single occurrence or used multiple time?" My response, "you can but it isn't proper." In short, you can use classes if you would like to but it may get complicated and you may end up changing things in multiple places if you are not careful.
As an example, if you have one CSS file for your entire site, you may get easily confused about which classes you used more than once. When you see IDs, you know that they are only used once, so you do not need to worry about it changing in multiple spots. I suppose if you insist on using CLASS for everything, make sure to be very descriptive with the names of the classes. The easiest solution, and the proper way to code CSS, is to use IDs for single occurrence elements and CLASS for multiple occurrences. Also, remember to be descriptive so that you can easily figure out where the element applies.
Also see: How do you Code your CSS? Here
No comments:
Post a Comment