PDA

View Full Version : CSS: Class Vs. ID


chilipie
11-21-2004, 08:54 PM
Like the title says - CSS: Class Vs. ID.

Which should I use, when and why?

I hope you guys can help clear this up for me :) ,

Ol.

Jalenack
11-21-2004, 09:00 PM
id is more specific...class is more general

Id will apply to the first element on the page that has the right id..
class will apply to as many elements on the page that have the right id

Also, ID's override classes..
i was just reading somewhere about it...i forget where tho :)


<div id="blue" class="red">blue text</div>
<div id="blue" class="red">red text</div>

and css

#blue {color: blue}
.red {color: red}

first line example above will be blue...second line example will be red because id only applys to the first element with the specified ID

<edit> Error is prolly right...my example might not be exactly true..its just how the validity works...</edit>

hope this helps!

gsnedders
11-21-2004, 09:04 PM
Hmm... Not sure how true that is...

You can only use a specific ID once, whereas you can use a class as often as you want.

eg. <p id="eg">A paragraph</p>
<p id="eg">Another paragraph</p>
Isn't vaild.

<p class="eg">A paragraph</p>
<p class="eg">Another paragraph</p>
Is valid.

gohankid77
11-21-2004, 09:28 PM
Error is correct. ID can only be used once per document. If you need to apply the same thing to several elements, use a CLASS.

As for specificity, ID is more specific than CLASS because of the fact that ID can only be used once on a specific element. CLASS is more general because it can be applied to several unrelated elements.

ID = once per document
CLASS = several times per document

css-discuss is a good site: http://css-discuss.incutio.com/?page=ClassesVsIds