select 第 n 个 child 从 2 级以上

select nth child from 2 levels up

我有这样的 html 结构:

<div class='parent'>
  <div class='row'>
    <div class='button'>
      button
    </div>
    <div class='button'>
      button
    </div>
  </div>
  <div class='row'>
    <div class='button'>
      button
    </div>
    <div class='button'>
      button
    </div>
  </div>
</div>

所以我们有 parent -> 行 -> 按钮,1 parent,2 行,每行有 2-4 个按钮。有没有我可以使用的 css 选择器(比如 nth-child),但它将所有按钮视为同级按钮(即使它们在不同的行中)?类似于:

.parent .child:nth-child(randomNum) {

}

其中 randomNum 是介于 1 和 numOfTotalButtons.length

之间的数字

使用兄弟选择器~

.row ~ .row > .button {
  color: hotpink;
}

.row ~ .row ~ .row > .button {
  color: blue;
}
<div class='parent'>
  <div class='row'>
    <div class='button'>
      button
    </div>
    <div class='button'>
      button
    </div>
  </div>
  <div class='row'>
    <div class='button'>
      button
    </div>
    <div class='button'>
      button
    </div>
  </div>
  <div class='row'>
    <div class='button'>
      button
    </div>
    <div class='button'>
      button
    </div>
  </div>
</div>

"is there a css selector I can use (like nth-child) but that treats all buttons as siblings (even if they're in different rows)?"

是的,class 选择器。除此以外,您还需要满足其他 and/or 情况吗?

.button {
  outline: red 3px solid;
}
<div class='parent'>
  <div class='row'>
    <div class='button'>
      button
    </div>
    <div class='button'>
      button
    </div>
  </div>
  <div class='row'>
    <div class='button'>
      button
    </div>
    <div class='button'>
      button
    </div>
  </div>
</div>

恐怕只用CSS是不行的。您可以使用 jQuery 或纯 javascript :

存档

//jQuery
$(".button").eq(0).css("color", "red");
$(".button").eq(1).css("color", "green");
//pure javascript
document.querySelectorAll(".button")[2].style.color = "blue";
document.querySelectorAll(".button")[3].style.color = "pink";
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='parent'>
  <div class='row'>
    <div class='button'>
      button
    </div>
    <div class='button'>
      button
    </div>
  </div>
  <div class='row'>
    <div class='button'>
      button
    </div>
    <div class='button'>
      button
    </div>
  </div>
</div>