Div id vs Div class

One of the most popular questions among webdesigners starting to learn CSS is: What is the difference between id and class?

First difference

Ids are to be used only once in your html layout. Classes can be used multiple times.

Generally ids are used for the main elements of the page, such as header, main content, sidebar, footer, etc. Classes are used for elements that will appear several times on your page, but can not be covered by standard html elements. For example menus. The easy way to remember which one of the two should be used only once to think of how many people are out there with your id card number.

Second difference

Ids have priority over classes. So, if an element has a both id and class, the id will take over.

Lets look at an example:
<!--CSS part:-->
<style type="text/css">
#greenidstyle {color:green}
.redclassstyle {color:red}
<!--HTML part:-->
<p id="greenidstyle">first line of copy for id</p>
<p class="redclassstyle">second line of copy for class</p>
<p id="greenidstyle" class="redclassstyle">third line of copy for combined</p>

And this is what you’re actually going to see:

first line of copy for id

second line of copy for class

third line of copy for combined

What happens here? In the first line we define an id to have font color green and the result is green. On the second line we define the class to have font color red and the result is red as expected. In the third line we have assigned both the class and the id to the text, but as you can see the result will actually be green because id takes precedence of over class.

Now, you’re probably saying, wait a minute – how can you add the same id to both the first and third line? You’re right – it’s something we should not do. I just did it for presentation purposes here. This code would work, but would not validate.