Skip to content Skip to sidebar Skip to footer

Whats The Difference Between Using .Class Or #ElementId In CSS?

Ive been wondering... in CSS are there any differences between creating a style class and applying it an element, or creating a style with the #elementId notation (apart from being

Solution 1:

An ID must be unique in a document. Classes can be used in any number and combination. So you can use one class on multiple elements and multiple classes on one element.


Solution 2:

One other difference; id-selectors are more specific than class-selectors, so I believe they will "trump" any other selector that exists. You can use "important" to do the same thing, but and id selector may be easier.

But id-selectors should be used sparingly...


Solution 3:

Many classes can include a given "class" while only one element may be identified by a given ID. If you need to locate an unique Element use ID, otherwise if you wish to mark many elements that are basically the same but in different spots in your html use 'class'.

You sort of answered your own question, they are just mechanisms to 'identify' elements.


Solution 4:

using #elementID applies only to the element uniquely identified by that id. a class can be used by multiple elements

there is however an order of precedence. selectors using the id have greater weight than selectors using class and when there is a collision the #id selector will take precedence

edit: see http://kiribao.blogspot.com/2008/03/css-selectors-precedence-and-ways-to.html for more detail on selector precedence

edit: also see the w3c specs at http://www.w3.org/TR/CSS21/cascade.html#specificity


Solution 5:

Performance or functionality-wise, there is no difference [citation needed].

The only real difference is semantic, if you are working on a single node with a unique ID, or if you need a reusable class marking several nodes.


Post a Comment for "Whats The Difference Between Using .Class Or #ElementId In CSS?"