New friends may encounter this situation when writing CSS: after hard work writing a line of CSS, you refresh the page and see, "OH! Shit! Why hasn't the page changed?"
For example!
HTML:
I am a list I am a list I am a list I am a list
CSS:
.nav li {color:red;}
.nav_active {color:yellow;}
This is a typical example. Of course, if you can accurately answer that the third list is red, then you can stop reading the subsequent content.~ Why isn't it yellow? This is a classic specificity issue.
Below is an article I once saw, I’ll post it here, for those who haven’t fully understood it yet! It’s been a while, and I can’t find the source anymore, I apologize to the original author~
---------Beautiful Divider----------
When selectors are the same, the latter will override the properties of the former. For example:
p { color: red; }
p { color: blue; }
The color of the p element will be blue, as it follows the latter rule.
However, you can't always achieve your goal by having the same conflicting selectors. When using nested selectors, reasonable conflicts arise. For example:
div p { color: red; }
p { color: blue; }
It may seem that the color of the p element within the div is blue, just like the following p element’s rule, but the specificity of the first selector is red. Essentially, the more specific a selector is, the styles will show when there is a style conflict.
The actual specificity of a set of nested selectors can be calculated. Basically, the value of using an ID selector is 100, a class selector is 10, and each HTML selector is 1. Adding them up gives the computed specificity value.
The specificity of p is 1 (one HTML selector)
The specificity of div p is 2 (two HTML selectors)
The specificity of .tree is 10 (one class selector)
The specificity of div p.tree is 1+1+10=12 (two HTML selectors, one class selector)
The specificity of #baobab is 100 (one ID selector)
The specificity of body #content .alternative p is 112 (two HTML selectors, one ID selector, one class selector)
According to the above rules, div p.tree has a higher specificity than div p, and body #content .alternative p is higher than both of them.