html - nth-of-type css 选择器以类的第一个元素为目标

标签 html css css-selectors

我试图理解为什么这个 nth-of-type 选择器没有按预期工作。我的目标是将第一个 .row 元素设为红色,在第一个蓝色元素之后将所有其他元素设为红色,同时让元素保持原样为绿色。

https://jsfiddle.net/darrengates/pa34zyjd/14/

.wrapper div {
  width: 200px;
  background-color: green;
  color: white;
  margin: 5px;
  padding: 5px;
}
.wrapper .row:nth-of-type(n+1) {
  background-color: red;
}
.wrapper .row:nth-of-type(n+2) {
  background-color: blue;
}
<div class="wrapper">
  <div class="option">option</div>
  <div class="button">some button</div>
  <div class="row">I wanna be red</div>
  <div class="row">I wanna be blue</div>
  <div class="row">I wanna be blue</div>
  <!-- all other row elements after the first should be blue -->
</div>

最佳答案

n-th-of-type 选择器指的是同一级别的标签类型不是类,在本例中div 标签是 .wrapper 中的兄弟标签。因此,您需要此 CSS,因为它们是其中的第三个和第四个 div:

.wrapper .row:nth-of-type(n+3) {
  background-color: red;
}
.wrapper .row:nth-of-type(n+4) {
  background-color: blue;
}

https://jsfiddle.net/cb3qd8t6/

关于html - nth-of-type css 选择器以类的第一个元素为目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42170661/

相关文章:

javascript - 如何获取引用中的引用文本?

jquery - 样式集菜单 jQuery 中的错误

html - 您可以使用 CSS 定位 ID 中的 ID 吗?

css - 只选择第一个元素,不考虑类型

jquery - css 选择器不是最后一个子元素不工作(需要纯 css 解决方案)

ruby-on-rails - 如何使用 Haml 呈现 bool 数据属性?

javascript - 单击动态生成的 anchor 标记时获取超链接文本

html - 添加 bootstrap css 时全高不起作用

Jquery动画背景

html - 无法将元素定位在左下角