I noticed that when using different methods to access the HTML element in the CSS, some selectors win over others.


Suppose in an empty HTML document there is a paragraph that has been assigned the class someclass .

The p: first-class pseudo- selector will be stronger than the .someclass class selector .

Now let's replace the class someclass with id.

The p: first-class pseudo- selector will be weaker than the id #someclass selector.


I would like to understand the logic of these priorities.
Is there any reference book, maybe a table, clearly demonstrating the priorities of some selectors over others?

(it seems that I came across a similar table of priorities for arithmetic and bitwise operations when I was learning javascript)

  • There is. The very first link in Google on request Priorities CSS selectors And on Habré was well painted. - Moonvvell
  • @Moonvvell, Thank you very much, this is what you need! - Rumata

1 answer 1

I do not know if it will help or not:

 * {} /* a=0 b=0 c=0 d=0 -> specificity = 0,0,0,0 */ li {} /* a=0 b=0 c=0 d=1 -> specificity = 0,0,0,1 */ li:first-line {} /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */ ul li {} /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */ ul ol+li {} /* a=0 b=0 c=0 d=3 -> specificity = 0,0,0,3 */ h1 + *[rel=up]{} /* a=0 b=0 c=1 d=1 -> specificity = 0,0,1,1 */ ul ol li.red {} /* a=0 b=0 c=1 d=3 -> specificity = 0,0,1,3 */ li.red.level {} /* a=0 b=0 c=2 d=1 -> specificity = 0,0,2,1 */ #x34y {} /* a=0 b=1 c=0 d=0 -> specificity = 0,1,0,0 */ style="" /* a=1 b=0 c=0 d=0 -> specificity = 1,0,0,0 */ <HEAD> <STYLE type="text/css"> #x97z { color: red } </STYLE> </HEAD> <BODY> <P ID=x97z style="color: green"> </BODY> 

A source

  • Thank you very much! An interesting resource. I understand correctly that a, b, c, d is like a priority category, a is the highest, d is the lowest? And d = 2 is greater than d = 1, and c = 1 is greater than d = 2 - right? - Rumata