首页 > 解决方案 > 当第一个和第二个按钮之间有另一个元素时,如何使用 nth-child 正确选择第二个按钮?

问题描述

我试图使用

.myDivName button:nth-child(2) {
  background-color: red;
}

选择我的第二个按钮,<div class="myDivName">但它不起作用。我的代码是 -

<div class="myDivName">
  <button>
    1
  </button>
  <input type="text">
  <button>
    2
  </button>
</div>

但我发现如果我删除了<input>中间的,那么 nth-child 就可以了。

如何使用 nth-child(2) 正确选择此按钮?如果 nth-child 不能使用,最好的方法是什么?

谢谢!

小提琴 - https://jsfiddle.net/e6au4hot/9/

标签: csscss-selectors

解决方案


改用nth-of-type

.hi > button:nth-of-type(2) {
  background-color: red;
}

jsFiddle 示例

您关心的是元素的类型,而不是层次结构中的位置


推荐阅读