Skip to content Skip to sidebar Skip to footer

Prioritize Id Selector Over An Id And Class

I have a situation in which I load a style with a selector that should be prioritized over another. The situation looks like the one in this fiddle, in which a specific id selector

Solution 1:

Simply use the :not selector to exclude the #hello element.

Change the first to:

#cont.hello:not(#hello) {
    color:red;
}

Demo Fiddle

More on :not from MDN

The negation CSS pseudo-class, :not(X), is a functional notation taking a simple selector X as an argument. It matches an element that is not represented by the argument. X must not contain another negation selector, or any pseudo-elements.


Alternatively- per the comments below, you can increase the specificity of the second selector whilst providing variations for various contexts:

#hello, #cont#hello, #hello.hello {
    color:blue;
}

Demo Fiddle

Solution 2:

I suggest you to add another id selector to the first set of CSS rules.

#cont#hello {
    color:blue;
   }

 #cont.hello {
    color:red;
   }

DEMOhttp://jsfiddle.net/a_incarnati/53q74jah/

In this case the color was overridden in red because you were using just one id selector #hello and that it's less specific than a selector with 2 ids combined or one id and one class combined, like you have done:

#cont.hello {
    color:blue;
}

One of the things to take into account when writing CSS code, it’s the concept of CSS specificity. Understanding well this concept will avoid you to have to use !important;

As Mozilla Developer Network defines it, specificity is nonetheless:

Specificity is the means by which a browser decides which property values are the most relevant to an element and gets to be applied. Specificity is only based on the matching rules which are composed of selectors of different sorts.

The following list of selectors is by increasing specificity:

  • Universal selectors
  • Type selectors
  • Class selectors
  • Attributes selectors
  • Pseudo-classes
  • ID selectors
  • Inline style

You can measure specificity counting how many selectors are present in a CSS statement.

CSS Specificity can be represented by 4 columns of priority:

inline=1|0|0|0

id=0|1|0|0

class=0|0|1|0

element=0|0|0|1

Left to right, the highest number takes priority.

enter image description here

Solution 3:

You don't need two different selectors. You can keep one:

.hello {
    color:red;
}
#cont.hello {
    color:blue;
}

http://jsfiddle.net/vkftfj2n/4/

Post a Comment for "Prioritize Id Selector Over An Id And Class"