外观
CSS选择器
约 566 字大约 2 分钟
2025-11-06
https://developer.mozilla.org/zh-CN/docs/Web/CSS/CSS_selectors
选择器优先级
元素选择器 < 类选择器 < ID选择器
选择器列表
- 元素选择器 p
- 类选择器 .text
- ID选择器 #text
- 属性选择器:根据元素的属性及其值来选择元素
- 精确匹配
[attribute="value"](如 [type="text"]) - 开头匹配
[attribute^="value"](如 [href^="https"]) - 结尾匹配
[attribute$="value"](如 [src$=".png"]) - 包含匹配
[attribute*="value"](如 [class*="btn"]) - 空格分隔值匹配
[attribute~="value"](如 [class~="active"]) - 连字符前缀匹配
[attribute|="value"](如 [lang|="en"])
- 精确匹配
- 伪类选择器:伪类选择器用于选择元素的特定状态或位置。
- https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes
- 伪元素选择器 first-line
- https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements
- 通配符选择器 *
计算规则
- ID选择器: +100
- 类/属性/伪类选择器: +10
- 元素/伪元素选择器: +1
- 组合器和通配符不增加特异性
比较规则
- 从左到右比较特异性值
- 值高的优先级高
- 完全相同时后定义的生效
Combinators and separators
- 后代组合器 A B: 选择所有被A包含的B元素(任意嵌套层级)
- 子元素组合器 A > B: 仅选择A的直接子元素B(仅第一层嵌套)
- 相邻兄弟组合器 A + B: 选择紧跟在A后面的第一个同级B元素
- 后续兄弟组合器 A ~ B: 选择A之后的所有同级B元素
- 组合器列表 A, B: 同时选择A、B元素
- 命名空间分隔器 namespace|element
| 类型 | 示例 |
|---|---|
| 标签选择器 | div, span |
| 类选择器 | .class |
| ID选择器 | #id |
| 通配符 | * |
| 属性选择器 | [attr], [attr="value"] |
| 伪类 | :hover, :first-child |
| 伪元素 | ::before, ::after |
| 后代选择器 | div span |
| 子选择器 | div > span |
| 相邻兄弟 | div + span |
| 通用兄弟 | div ~ span |
| 组合选择器 | div, span |
| 嵌套选择器 | & |
| 注释 | /* comment */ |
伪类
- :active
- :any-link
- :autofill
- :buffering
- :checked
- :default
- :defined
- :dir()
- :disabled
- :empty
- :enabled
- :first-child
- :first-of-type
- :focus
- :focus-visible
- :focus-within
- :fullscreen
- :future
- :has()
- :hover
- :in-range
- :indeterminate
- :invalid
- :is()
- :lang()
- :last-child
- :last-of-type
- :link
- :modal
- :muted
- :not()
- :nth-child()
- :nth-of-type()
- :nth-last-child()
- :nth-last-of-type()
- :only-child
- :only-of-type
- :open
- :optional
- :out-of-range
- :past
- :paused
- :picture-in-picture
- :placeholder-shown
- :playing
- :popover-open
- :read-only
- :read-write
- :required
- :root
- :scope
- :seeking
- :stalled
- :target
- :user-invalid
- :user-valid
- :valid
- :visited
- :volume-locked
- :where()
