外观
CSS选择器
约 399 字大约 1 分钟
2025-11-06
CSS 选择器模块定义了选择元素的模式,然后应用一组 CSS 规则及其特异性 。CSS 选择器模块为我们提供了 60 多个选择器和五个组合器。 其他模块提供额外的伪类选择器和伪元素。
在 CSS 中,选择器是用于匹配或选择要设置样式的元素的模式。JavaScript 中还使用选择器来选择要作为 NodeList 返回的 DOM 节点。
选择器,无论是在 CSS 还是 JavaScript 中使用,都可以根据 HTML 元素的类型、属性、当前状态甚至在 DOM 中的位置来定位 HTML 元素。组合器允许您根据元素与其他元素的关系选择元素,从而在选择元素时更加精确。
https://developer.mozilla.org/zh-CN/docs/Web/CSS/CSS_selectors
| 类型 | 示例 |
|---|---|
| 标签选择器 | div, span |
| 类选择器 | .class |
| ID选择器 | #id |
| 通配符 | * |
| 属性选择器 | [attr], [attr="value"] |
| 伪类 | :hover, :first-child |
| 伪元素 | ::before, ::after |
| 后代选择器 | div span |
| 子选择器 | div > span |
| 相邻兄弟 | div + span |
| 通用兄弟 | div ~ span |
| 组合选择器 | div, span |
| 嵌套选择器 | & |
| 注释 | /* comment */ |
Selectors :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() Attribute selectors Class selector ID selectors Type selectors Universal selectors
