tags:

views:

48

answers:

3

Is using css .class in place of #id always a better idea to get rid of style overriding problems and iimportant?

#content ul li a {font-size:10px}

#content .demo ul li a {font-size:15px}
+2  A: 

id is the identifier and ideally it should be used only for one element whereas class can be used multiple times for multiple elements.

SEE: Id vs Class

that i know the problem is if something is defined in #id then it will override on .class also, if .class is inside that #id
metal-gear-solid
my question is different.
metal-gear-solid
A: 

No, I think it isn't. IDs should be used for unique elements only that are going to be addressed using JavaScript IMO.

They have higher specificity than classes when the importance of a CSS rule is calculated but that is no argument for using them.

Pekka
how to style differently. in my example.? size of id is overriding on class
metal-gear-solid
How to deal this situation without using `!important`?
metal-gear-solid
@metal if that is your situation, it may be perfectly fine to use the `id`. If it's there in the source code, it's there and there is nothing wrong with addressing it in CSS. I would just not start introducing IDs with the sole purpose of achieving the desired CSS result.
Pekka
@-pekka - i think you are not getting situation. I defined style for #content li now i'm making a #tab inside #content. The problem is whatever is written for #content li is overriding on #tab li.
metal-gear-solid
@metal ahh I see. Can you post a full HTML and CSS snippet? It's hard to tell from what you posted. I may be able to take a look at it later today if it's still current then.
Pekka
See this example to understand problems http://jsbin.com/oreqe/4 second line should be blue.
metal-gear-solid
@metal I see. Do you control the HTML? How about switching to a class instead of an ID? Then the override should work.
Pekka
+1  A: 

A class won't always override an ID - given two conflicting rules for the same element, the browser will calculate a score for each rule based on the specificity of the rule. Each part of the rule is awarded points, then the rule with the most points applied.

  • html selectors (div, p, etc) are +1
  • class selectors (.class) are +10
  • id selectors (#id) are +100

So for your example:

#content ul li a {font-size:10px} = 100 + 1 + 1 + 1 = 103
#content .demo ul li a {font-size:15px} = 100 + 10 + 1 + 1 + 1 = 113

Hope that helps

adam