Div's class vs id

Use id to identify elements that there will only be a single instance of on a page. For instance, if you have a single navigation bar that you are placing in a specific location, use id="navigation".

Use class to group elements that all behave a certain way. For instance, if you want your company name to appear in bold in body text, you might use <span class='company'>.


The most important thing to understand is that IDs have to be unique: only one element with a given ID should exist within a page. Thus, if you're wanting to refer to a specific page element, that's often the best thing to use.

If you have multiple elements that are in some way similar, you should use the elements class to identify them.

One very useful, surprisingly little known fact is that you can actually apply multiple classes to a single element by putting spaces between the class names. Thus, if you posted a question that was written by the currently logged in user, you might identify it with <div class="question currentAuthor">.


Think of University.

<student id="JonathanSampson" class="Biology" />
<student id="MarySmith" class="Biology" />

Student ID cards are distinct. No two students on campus will have the same student ID card. However, many students can and will share at least one Class with each other.

It's okay to put multiple students under one Class title, Biology 101. But it's never acceptable to put multiple students under one student ID.

When giving Rules over the school intercom system, you can give Rules to a Class:

"Would the Biology class please wear Red Shirts tomorrow?"

.BiologyClass {
  shirt-color:red;
}

Or you can give rules to a Specific Student, by calling his unique ID:

"Would Jonathan Sampson please wear a Green Shirt tomorrow?"

#JonathanSampson {
  shirt-color:green;
}

IDs must be unique but in CSS they also take priority when figuring out which of two conflicting instructions to follow.

<div id="section" class="section">Text</div>
#section {font-color:#fff}
.section {font-color:#000}

The text would be white.


An additional benefit to using an ID is the ability to target it in an anchor tag:

<h2 id="CurrentSale">Product I'm selling</h2>

Will allow you to in some other place link directly to that spot on the page:

<a href="#CurrentSale">the Current Sale</a>

A common use for this would be to give each headline on a blog a datestamped ID (say id="date20080408") which would allow you to specifically target that section of the blog page.

It is also important to remember that there are more restricted naming rules for ids, primarily that they can't start with a number. See similar SO question: What is a valid value for id attributes in html