第 8 课 3 / 18 | 编码:L08-07
核心知识

属性选择器与组合选择器

看同一段 HTML:按属性找元素,与按嵌套关系找元素,有什么不同?

同一份 HTML

<input type="email">
<input type="text">

<section class="panel">
  <p class="card">A</p>
  <div>
    <p class="card">B</p>
  </div>
</section>

A 的父元素是 section;B 的父元素是 div。A、B 都位于 section 内部。

① 属性选择器:看属性值

input[type="email"]

选中所有 type 值为 email 的 input,不选 type="text" 的输入框。按属性值匹配,与排列顺序无关。

② 后代选择器:中间是空格

.panel .card

选中 .panel 内部的 .card,允许隔着其他元素。A、B 都选中。

③ 子元素选择器:中间是 >

.panel > .card

只选父元素就是 .panel 的 .card。选中 A,不选 B:B 中间隔了一层 div。

展开完整代码与运行演示
<style>
  .card {
    background: #e8f2f5;
    margin: 12px 0;
  }

  input[type="email"] {
    border-color: #1765d9;
  }

  .panel > .card {
    padding: 1rem;
  }
  .panel .card {
    color: teal;
  }
</style>

<label>
  邮箱
  <input type="email">
</label>
<label>
  文本
  <input type="text">
</label>

<section class="panel">
  <p class="card">A</p>
  <div>
    <p class="card">B</p>
  </div>
</section>