<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Basic selectors</title>
<style>
* { box-sizing: border-box; } /* universal: every element */
p { margin: 6px 0; } /* type: every <p> */
.tip { background: #e5e7eb; padding: 6px; } /* class */
#main-title { color: #2563eb; } /* ID: one element */
h2, .lead { font-style: italic; } /* group: either one */
</style>
</head>
<body>
<h1 id="main-title">Selectors</h1>
<p class="lead">A lead paragraph (grouped with h2).</p>
<p class="tip">A tip, matched by .tip</p>
<h2>A subheading</h2>
<p>A plain paragraph.</p>
</body>
</html>
选择器类型一览
选择器
示例
匹配
通配符选择器
*
每一个元素
元素选择器
p
每一个 <p>
类选择器
.tip
带有 class="tip" 的元素(可以同时有其他类)
ID 选择器
#main-title
id="main-title" 的元素
属性选择器
[type="email"]
属性匹配的元素
伪类
a:hover、li:first-child
处于某种状态或位置的元素
伪元素
p::first-line、.x::before
元素的某个部分
分组
h1, h2, h3
匹配列表中任意一项的元素
复合选择器
p.tip
同时带有该类的 <p>
类和 ID 有专门的页面:CSS 类选择器。:nth-child() 和 :not() 等伪类在伪类页面中介绍。
组合器:后代与子元素
组合器根据两个选择器在 HTML 树中的关系把它们连接起来。一共有四种。
组合器
语法
何时匹配 B
后代组合器
A B(空格)
B 位于 A 内部的任意位置
子元素组合器
A > B
B 的父元素是 A
相邻兄弟组合器
A + B
B 紧跟在 A 后面,父元素相同
通用兄弟组合器
A ~ B
B 位于 A 之后的某处,父元素相同
空格和 > 是大家最容易混淆的一对。后代选择器可以深入任意层级;子元素选择器只往下找一层:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Child selector</title>
<style>
li { padding: 2px 6px; margin: 2px 0; }
.all li { background: #e5e7eb; } /* descendant: every level */
.direct > li { border-inline-start: 4px solid #2563eb; } /* child: top level only */
</style>
</head>
<body>
<ul class="all direct">
<li>Top level: gray and blue edge</li>
<li>Top level: gray and blue edge
<ul>
<li>Nested: gray only</li>
<li>Nested: gray only</li>
</ul>
</li>
</ul>
</body>
</html>
兄弟组合器:+ 与 ~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Siblings</title>
<style>
p { margin: 4px 0; padding: 4px 8px; }
h2 + p { background: #f59e0b; } /* only the first p after h2 */
h2 ~ p { color: #2563eb; } /* every p after h2 */
</style>
</head>
<body>
<p>Before the heading: untouched.</p>
<h2>Heading</h2>
<p>Right after h2: amber and blue.</p>
<p>Later sibling: blue only.</p>
<p>Later sibling: blue only.</p>
</body>
</html>
兄弟组合器只向后查找。没有“前一个兄弟”组合器,不过可以用 :has() 来表达:h2:has(+ p) 匹配紧接着跟有一个 p 的 h2。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Space matters</title>
<style>
p.note { background: #e5e7eb; } /* a p that has .note */
p .note { color: #16a34a; font-weight: bold; } /* a .note inside a p */
</style>
</head>
<body>
<p class="note">p.note: gray background</p>
<p>Plain p with a <span class="note">span.note inside</span></p>
</body>
</html>
浏览器如何读取选择器
当多条规则匹配同一个元素并设置同一个属性时,优先级更高的选择器胜出;优先级相同时,后写的规则胜出。一个 ID 的分量超过任意数量的类,一个类的分量超过任意数量的元素选择器;完整的优先级表见 !important 页面。