选择器
组合器与特异性。
选择器
这一课你将能做到
- 熟练使用元素、类、ID、属性、伪类、伪元素六类选择器
- 用组合器(后代、子代、兄弟)精确表达元素关系
- 手算任意两条选择器的特异性,预判谁会生效
为什么要学
选择器是 CSS 的「瞄准系统」。写 CSS 一半时间在写选择器:选不准就染错颜色,选太宽就误伤一片。面试里特异性计算是必考题。
人话:选择器就像快递地址——写得越精确,包裹送得越准;写「中国」就送错,写「北京市海淀区xx小区3栋501」才到位。
先建立图像
<style>
p { color: gray; } /* 元素 */
.highlight { background: yellow; } /* 类 */
#main { font-size: 20px; } /* ID */
a[target] { color: red; } /* 属性 */
li:first-child { font-weight: bold; } /* 伪类 */
p::first-line { text-transform: uppercase; } /* 伪元素 */
</style>
<div id="main">
<p class="highlight">第一段,类 highlight</p>
<p>第二段,<a href="#" target="_blank">带 target 的链接</a></p>
<ul><li>列表第一项</li><li>列表第二项</li></ul>
</div>
浏览器渲染后:
第一段,类 highlight ← 黄底、灰字、20px
第二段,带 target 的链接 ← 链接红色
• 列表第一项 ← 加粗
• 列表第二项
跟着做
步骤 1:基础三剑客
/* 元素选择器:选中所有该标签 */
p { color: #333; }
/* 类选择器:. 开头,最常用 */
.card { padding: 16px; }
/* ID 选择器:# 开头,页面唯一 */
#header { height: 60px; }
类名建议小写加连字符:.user-card、.btn-primary。
步骤 2:属性选择器
input[type="text"] { border: 1px solid #ccc; } /* 精确匹配 */
a[href^="https"] { color: green; } /* 以 https 开头 */
a[href$=".pdf"] { color: orange; } /* 以 .pdf 结尾 */
img[alt*="logo"] { border: none; } /* 包含 logo */
实战场景:表单样式按 type 区分、外链自动加图标。
步骤 3:伪类(描述元素状态)
a:hover { color: red; } /* 鼠标悬停 */
input:focus { outline: 2px solid blue; } /* 获得焦点 */
li:first-child { margin-top: 0; } /* 第一个子元素 */
li:last-child { margin-bottom: 0; } /* 最后一个 */
li:nth-child(2n) { background: #f5f5f5; } /* 偶数项,斑马纹 */
button:disabled { opacity: 0.5; } /* 禁用态 */
nth-child 接受 2n、2n+1、odd、even、具体数字。
步骤 4:伪元素(创建虚拟元素,用双冒号)
p::first-line { font-weight: bold; } /* 首行 */
p::first-letter { font-size: 2em; } /* 首字母,做首字下沉 */
.quote::before { content: "「"; }
.quote::after { content: "」"; }