css - 为什么 CSS 相邻组合器在这里不起作用?

标签 css

谁能帮我理解为什么下面的相邻组合符 (+) 不能用作 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/

相关文章:

html - Float 在 IE 7 和 IE 8 中看起来不同(html 验证)

css - 带有图像的自定义网格 - 响应问题

css - 我的伪类 :not with input element isn't working correctly

html - 为什么 min-height on parent 不能防止 100% height child 崩溃

html - 如何使用 CSS 调整电子邮件中动态图像的大小?

html - 如何水平对齐单元格内的三个跨度并在跨度中添加内部填充

javascript - 倒数计时器,setDate 有问题

css - 为什么溢出: hidden add padding/margin?

css - p-tag 中的中心字母,具有像素定义的宽度和高度

html - 使左右导航栏绝对化?