First of all, they are both selectors. But they are very different:
1) IDs are unique identifiers;
2) classes are not unique.
The above first difference is quite important because we can give a unique identifier to just one page element, while we can give a class to more than one element.
Imagine we have one span and two divs. We can give the span and one div a class, and an ID to the other span:
So we can make the first two tags red and the third blue using something like:
And the result will be:
That's basic, isn't it? I believe we all know about this big difference, but for the beginners out there, I thought it was important to make it clear.
So just remember: you cannot give the same ID to two elements.
Another difference is quite clear from the above code: while classes in CSS are defined with a starting dot (".spanDiv"), IDs start with a "#" ("#justDiv"). Obviously classes are given as class="className" while IDs as id="idName".
The above differences are what we all need to know in order to understand when to use IDs and when to use classes.
Because a class can be used several times, we use them when we need to apply a specific style rule to different elements. On the other hand, IDs are used when a rule should be applied just to one element, being sure that it won't be applied to anything else.
In the past, web developers suggested to use IDs and not classes. That's because, CSS was mainly embedded in each web page. Today, I believe the above rule doesn't apply anymore. In fact we use linked CSS stylesheets, global rules across the whole site. That is why I suggest to use both IDs and classes, depending on the related situation.
Can we use IDs and classes together?
Oh yes, we can. And some times it is very convenient.
Let's say we have a list of elements (three divs with red font), but just the middle one should be bold:
<div class="red" id="bold">Two</div>
As a last thing.. do not use selectors (either IDs or classes) when we don't need them. Remember that we can select an element by its tag. If we need to style all the links in a page, we don't really need to give every <a> tag a class or an ID... just select the <a> tag.
That's all for today.
See you next time!