Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS How to Make a Website Debugging HTML and CSS Problems How to Fix Problems with Code

Id vs Class

Could someone give me a concise explanation of the difference between an Id and a Class? In what scenarios would you use each of them and why one over the other?

4 Answers

William Li
PLUS
William Li
Courses Plus Student 26,868 Points
  • class, you can assign same class to as many element as you like.
  • id, must be unique, you can only assign 1 id to 1 element.

So, the difference between class and id is many VS one.

Think of it like a school, Many students can attend the same class, but each student must have 1 unique student id.


Also, id can be used as fragment in the URL, Take a look at this link http://en.wikipedia.org/wiki/Treehouse_%28company%29#Culture, It's Treehouse's Wiki page. Notice the #Culture at the end? that's the id of an element on the page, when you append it at the end of URL, it takes you straight to that section of the page.

Dani Ivanov
Dani Ivanov
10,732 Points

Hi Patrick,

The main difference is that you can only use IDs once within your document while classes you can use multiple times.

So for example you can use ID to divide your document into sections e.g; Header, Navigation, Footer, Sidebar etc.

Classes can be used multiple times. For example lets say you have a class and within it you have styles for a simple button. Now every time you want to make something a button you can simply add that class to the text. Make sense?

Or if you have important text that you want to be red on more than one place within your page you can simply create one class and within your html document add class="something" to each paragraph/text you want to appear red.

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,253 Points

Hi Patrick! :)

Id's and classes are ways we can select elements in CSS.

An ID is a unique identifier for an element, where was a class is an identifier that can be appied to many elements. So you can only use an id once but you can use the same class many times.

Here's how to select elements via their id and their class.

#name {}

<div id="name"></div>

.navLink {}

<a class="navLink></a>

Thanks guys! Much appreciated :)