CSS Specificity
一句话解释
CSS specificity 是 scoring 系统那个 determines 哪个 CSS 规则 wins 当多个规则目标相同元素.
用大白话说
When multiple CSS rules apply to the same element, the browser needs to decide which one wins. It uses a scoring system called "specificity" — the rule with the highest score takes precedence.
Specificity is calculated as a three-part score (a-b-c): IDs count as (1-0-0), classes/attributes/pseudo-classes count as (0-1-0), and elements/pseudo-elements count as (0-0-1). For example, #请求头 .title has specificity (1-1-0), while div.title has (0-1-1). The higher score wins.
Inline styles (样式="...") override everything except !重要. The !重要 flag overrides normal specificity but should be used sparingly. Understanding specificity is essential for debugging why styles are not applying as expected.
示例
/* Specificity: 0-0-1 */
p { color: red; }
/* Specificity: 0-1-0 — wins over p */
.text { color: blue; }
/* Specificity: 1-0-0 — wins over .text */
#intro { color: green; }Three 规则使用 increasing specificity. ID selector wins and paragraph 是 green.
相关术语
相关资源
相关课程
- CSS Selectors
Selectors and specificity.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。