Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which CSS selector is stronger? [duplicate]

Which selector is stronger?

#nav li.current

or

div #nav li

and second

a.test

or

.test .test

What is the answer?

like image 897
jcubic Avatar asked Oct 01 '13 13:10

jcubic


People also ask

Which selector has the strongest selector specificity?

ID selectors have the highest specificity amongst the CSS selectors: 1, 0, 0, 0. Because of the unique nature of the ID attribute definition, we are usually styling a really specific element when we call up the ID in our CSS. – The specificity is 1, 0, 0, 1 because we have a type selector and an ID selector.

Which CSS selector has the highest precedence?

Id selector has highest priority because of unique nature of the ID attribute definition. We have two classes with one ID selector here it will apply font-size:12px and font-weight:500 due to the specificity rule as ID selector has highest priority after inline CSS.

Which is the best selector in CSS?

Class selector is the most useful common selector used by the developers. You can define the class selector using period (.) followed by the class name. It gives styling to all elements with a specified class attribute.

Which selector is faster in CSS?

popupbutton is the fastest.


2 Answers

From the spec:

A selector's specificity is calculated as follows:

  • count the number of ID selectors in the selector (= a)
  • count the number of class selectors, attributes selectors, and pseudo-classes in the selector (= b)
  • count the number of type selectors and pseudo-elements in the selector (= c)
  • ignore the universal selector

Selectors inside the negation pseudo-class are counted like any other, but the negation itself does not count as a pseudo-class.

Concatenating the three numbers a-b-c (in a number system with a large base) gives the specificity.

Examples:

*               /* a=0 b=0 c=0 -> specificity =   0 */
LI              /* a=0 b=0 c=1 -> specificity =   1 */
UL LI           /* a=0 b=0 c=2 -> specificity =   2 */
UL OL+LI        /* a=0 b=0 c=3 -> specificity =   3 */
H1 + *[REL=up]  /* a=0 b=1 c=1 -> specificity =  11 */
UL OL LI.red    /* a=0 b=1 c=3 -> specificity =  13 */
LI.red.level    /* a=0 b=2 c=1 -> specificity =  21 */
#x34y           /* a=1 b=0 c=0 -> specificity = 100 */
#s12:not(FOO)   /* a=1 b=0 c=1 -> specificity = 101 */
like image 98
user247702 Avatar answered Oct 07 '22 17:10

user247702


You can follow the following rules to calculate selectors as points.

A tag selector is worth 1 point.

A class selector is worth 10 points.

An ID selector is worth 100 points.

An inline style is worth 1,000 points.

#nav li.current = 100 + 1+10 = 111

div #nav li = 1 + 100 + 1 = 102

a.test = 1+10 = 11

.test .test = 10+10 = 20

like image 40
lvarayut Avatar answered Oct 07 '22 18:10

lvarayut