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;
}

Tags:

Css

Class

Xhtml