Specificity
Specificity is calculated by assigning a heavier weight to those selectors that are more specific in nature.
Tag-name or type selectors are not very specific. A website could have hundreds of
<p>
tags embedded in it making it difficult to target selected groups of them.The
class
attribute increases specificity by targeting subsets of elements that have common styling rules beyond the element selector.The
id
attribute of an element should be unique within a website making it very specific giving it the highest priority.Finally, if an element has inline styling
<p style=“color: brown”>
it automatically overrides all others.
Where specificity is determined to be equal between two competing declaration, the last declaration wins.
To calculate specificity, we count the occurrences of each selector and order them from highest to lowest using the following formula:
inline-style id class tag-name
Specificity Calculator
权重规则总结:
!important 优先级最高,但也会被权重高的important所覆盖
行内样式总会覆盖外部样式表的任何样式(除了!important)
单独使用一个选择器的时候,不能跨等级使css规则生效
如果两个权重不同的选择器作用在同一元素上,权重值高的css规则生效
如果两个相同权重的选择器作用在同一元素上:以后面出现的选择器为最后规则.
权重相同时,与元素距离近的选择器生效
!important>行内样式>ID选择器 > 类选择器 | 属性选择器 | 伪类选择器 > 元素选择器
Last updated