CSS 选择器有哪些类型
What are the different types of CSS selectors?
一句话:按「选中什么」分五类 —— 基础、组合、属性、伪类、伪元素。
- 基础:标签
div、 类.card、id#app、 通用* - 组合:后代
a b(空格)、 直接子元素a > b、 紧邻兄弟a + b、 后面所有兄弟a ~ b - 属性:
[type="text"]、[href^="https"](开头)、[class*="btn"](包含) - 伪类(状态):
:hover、:focus、:nth-child(2n)、:not(.on)、:disabled - 伪元素(造出不存在的元素):
::before、::after、::placeholder、::selection
会追问优先级怎么算—— 这才是真考点。按三位数比大小(id, class, 标签),从左往右比,高位一个也顶不过低位一万个:
| 选择器 | (id, class, 标签) |
|---|---|
div p | 0, 0, 2 |
.card p | 0, 1, 1 |
.card.on | 0, 2, 0 |
#app p | 1, 0, 1 ← 赢过上面所有 |
伪类算一个 class,伪元素算一个标签,:not() 本身不算分但括号里的算。 行内 style 比任何选择器都高,!important 再高一层 ——但别把 !important 当解法, 它通常说明选择器设计已经失控了。
同分怎么办?后写的赢。 这就是为什么覆盖第三方样式时, 把自己的 CSS 放在后面加载往往就够了。
In one line: five families, grouped by what they select — basic, combinator, attribute, pseudo-class, pseudo-element.
- Basic: type
div, class.card, id#app, universal* - Combinators: descendant
a b(space), direct childa > b, adjacent siblinga + b, all following siblingsa ~ b - Attribute:
[type="text"],[href^="https"](starts with),[class*="btn"](contains) - Pseudo-classes (state):
:hover,:focus,:nth-child(2n),:not(.on),:disabled - Pseudo-elements (invent an element):
::before,::after,::placeholder,::selection
The real question is specificity. Compare three numbers — (id, class, type) — left to right, and one high digit beats ten thousand low ones:
| Selector | (id, class, type) |
|---|---|
div p | 0, 0, 2 |
.card p | 0, 1, 1 |
.card.on | 0, 2, 0 |
#app p | 1, 0, 1 ← beats all of the above |
A pseudo-class counts as a class, a pseudo-element as a type, and :not() itself scores nothing but its argument does. Inline style outranks any selector, and !important outranks that — but do not treat !important as a solution; it usually means your selector design has already gone out of control.
What if they tie? The one written later wins. That is why loading your own CSS after a third-party stylesheet is often all you need.