Skip to content

CSS 选择器

选择器用于指定“哪些元素”应用样式。选择器写得清晰、稳定,CSS 才更容易维护。

1. 基础选择器

css
/* 元素选择器 */
p {
  color: #333;
}

/* 类选择器 */
.button {
  padding: 8px 12px;
}

/* ID 选择器 */
#header {
  border-bottom: 1px solid #e5e7eb;
}

/* 通配选择器 */
* {
  box-sizing: border-box;
}

2. 组合与分组

css
/* 复合选择器:同时满足元素和类 */
button.primary {
  background: #2563eb;
}

/* 分组选择器:多个目标共用同一套样式 */
h1,
h2,
h3 {
  line-height: 1.25;
}

3. 后代与子代

css
/* 后代选择器:匹配 nav 下任意层级的 a */
nav a {
  text-decoration: none;
}

/* 子代选择器:只匹配直接子元素 */
.card > .title {
  font-weight: 600;
}

4. 兄弟选择器

css
/* 相邻兄弟:只匹配紧接着的一个兄弟元素 */
h2 + p {
  margin-top: 8px;
}

/* 通用兄弟:匹配后续所有同级兄弟 */
.alert ~ p {
  color: #b91c1c;
}

5. 属性选择器

css
/* 含某属性 */
a[target] {
  color: #1d4ed8;
}

/* 精确匹配 */
input[type="email"] {
  border-color: #94a3b8;
}

/* 前缀 / 后缀 / 包含 */
a[href^="https"] { }
img[src$=".webp"] { }
a[href*="example"] { }

6. 伪类(Pseudo-class)

css
a:hover {
  text-decoration: underline;
}

input:focus {
  outline: 2px solid #2563eb;
}

li:first-child { }
li:last-child { }
li:nth-child(2n) { }
li:nth-of-type(3) { }

常见伪类::hover:focus:active:disabled:nth-child()

7. 伪元素(Pseudo-element)

css
.badge::before {
  content: "NEW";
  margin-right: 4px;
}

p::first-line {
  font-weight: 600;
}

::selection {
  background: #fde68a;
}

常见伪元素:::before::after::first-line::first-letter::selection

8. 优先级(Specificity)

从高到低:

  1. 行内样式(style
  2. ID 选择器(#id
  3. 类 / 属性 / 伪类(.class[type]:hover
  4. 元素 / 伪元素(div::before

示例:

css
#nav .link:hover { }
ul.menu > li.item a { }
.content p:first-child::first-line { }

9. 实践建议

  • 优先使用类选择器,减少对 ID 和深层嵌套的依赖
  • 控制选择器层级,建议不超过 3 层
  • 为组件写“可预测”的选择器,避免和页面级样式互相污染
  • 与命名规范(如 BEM)配合使用,降低维护成本

Released under the MIT License.