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

HTML How to Make a Website CSS: Cascading Style Sheets Use ID Selectors

Does it matter if you use <div id=""> or <div class=""> ?

I've previously been taught to use <div class="">, but wasn't sure if it really mattered.

Also, to select said <div> in the CSS file, I was taught to use .divname rather than #divname.. does that matter, too?

2 Answers

Steven Parker
Steven Parker
231,236 Points

Either can be used as a CSS selector.

But remember that an id must be unique. The element you give it to will be the only one on the whole document that has it. And every element can have (at most) only one ID.

But a class, on the other hand, can be shared by any number of elements of any type. And each element can have more than one class.

So while both can be used to select elements in CSS rules, the difference is that an id is always unique, and a class can be shared. And as Christopher pointed out, they have different identifying tokens in the selectors ("#" for id, "." for class).

mystyles.css
/* there can be only one green element with the id "greenone" */
#greenone { color: green; }

/* but there might be many blue elements with the class "imblue" */
.imblue { color: blue; }

/* there could also be many bold elements with the class "heavy" */
.heavy{ font-weight: bold;}
test.html
<p class="imblue">Here's an element with a class</p>
<p class="imblue heavy">Here's an element with <i>two</i> classes</p>
<p id="greenone" class="heavy">And this element has both an id and a class</p>
Christopher Jr Riley
Christopher Jr Riley
35,874 Points

For your first question: no. CSS won't care whether you're using the "id" or "class" attributes, as (within the context of CSS anyway) there's not much of a difference with respect to what to you can do after referencing them in the CSS file.

I say "not much" because there's a difference with respect to how you reference the div's attributes (I believe the following should answer your second question). For "id", as you saw in Nick's example, you write it out like this in CSS:

#wrapper {
    // styles go here...
}

As for the "class" attribute, it's slightly different:

.wrapper { 
    // styles go here...
}

So to answer your second question, yes it does matter, but only if you're dealing with a id or class.

I hope this helps answer your questions.