① 属性选择器:看属性值
input[type="email"]
选中所有 type 值为 email 的 input,不选 type="text" 的输入框。按属性值匹配,与排列顺序无关。
看同一段 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>