谁能帮我理解为什么下面的相邻组合符 (+) 不能用作 css 的注释部分。
相邻组合符 (+) 应该匹配第二个选择器 .btn
如果它立即在第一个选择器之后,即 .btn-group
根据 https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors所以我期待我的第一个 btn 的背景变成蓝色。
<div class="btn-group">
<button class="btn">
Save
</button>
<button class="btn">
Revert
</button>
</div>
/* .btn-group .btn:first-child {
background-color: blue;
color: white;
} */
.btn-group + .btn {
background-color: blue;
color: white;
}
最佳答案
adjacent sibling combinator (+
)只针对紧接在前面的 sibling 元素,而不是 child 元素。这可以从以下方面看出:
.btn-group + .btn {
background-color: blue;
color: white;
}
<div class="btn-group">
<button class="btn">
Save
</button>
<button class="btn">
Revert
</button>
</div>
<button class="btn">
Target
</button>
如果你想定位第一个 child ,那么你确实需要使用.btn-group .btn:first-child
。您可以在 child combinator (>
) 中添加 如果需要,使用 .btn-group > .btn:first-child
增加特异性:
span {
background-color: red;
}
/* Higher specificity with the child combinator */
.btn-group > .btn:first-child {
background-color: blue;
color: white;
}
<div class="btn-group">
<button class="btn">
Save
<span class="btn">Sub-class</span>
</button>
<button class="btn">
Revert
</button>
</div>
添加子组合器可以避免除子项之外的任何后代也应用规则,这在与伪选择器 :first-child
结合使用时可能会造成混淆。 ,如以下示例所示:
span {
background-color: red;
}
/* Higher specificity without the child combinator */
.btn-group .btn:first-child {
background-color: blue;
color: white;
}
<div class="btn-group">
<button class="btn">
Save
<span class="btn">Sub-class</span>
</button>
<button class="btn">
Revert
</button>
</div>
希望对您有所帮助! :)
关于css - 为什么 CSS 相邻组合器在这里不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46395610/