CSS 选择器
Nov 02, 2020 • 🍻 02min 46s read
🔖 webfrontendcss
选择器优先级
¶CSS 选择器类型的优先级:
内联样式
ID 选择器
类选择器
标签选择器
具体计算规则如下,其中
将作为向量比较大小,即左侧的数值有绝对优先权A specificity is determined by plugging numbers into
:- If the styles are applied via the style attribute,
; otherwise, . is equal to the number ofID selectors
present. is equal to the number ofclass selectors
,attribute selectors
, andpseudo classes
present. is equal to the number oftype selectors
andpseudo elements
present.
- If the styles are applied via the style attribute,
以下选择符对优先级没有影响
- 通配选择符 (universal selector):
*
- 关系选择符 (combinators):
+
,>
,~
,||
- 否定伪类 (negation pseudo-class):
:not()
但是在not()
内部声明的选择器会影响优先级
- 通配选择符 (universal selector):
栗子
Selector Specificity div
div span
div > span ~ i
div button[type="button"]
div.container
div .container.container
.container.container
.container.container div
.container .container div
#container
#container a:hover
特殊规则
¶!important
: 此声明将覆盖任何其它声明内联样式中使用
!important
无法被覆盖属性直接的约束可能越过优先级规则,比如
max-width
强于width
,因此下面的样式中即便声明了width: 500px !important;
(React 的style
属性不支持important
声明),最终的效果也只是200px
,因为max-width
拥有更强的约束:类似的,
width
和min-width
,height
和max-height
,height
和min-height
也满足此类约束。
Related
¶