nth-child从多级div中选择错误的元素

时间:2014-12-05 13:28:05

标签: html css css3 css-selectors pseudo-class

我有一些div个带有2个classess - 所有这些都有ticket个类,其中一些有visible类:

<div class="ticket hidden">BLA 1</div>
<div class="ticket hidden">BLA 2</div>
<div class="ticket hidden">BLA 3</div>
<div class="ticket visible">BLA 4</div>
<div class="ticket visible">BLA 5</div>
<div class="ticket visible">BLA 6</div>
<div class="ticket visible">BLA 7</div>
<div class="ticket visible">BLA 8</div>

当我通过以下方式解决时:

.visible:nth-child(5) {
 text-decoration: underline;
}

我得到了BLA 5,我想要BLA 8

我如何处理特定的.visible元素?

JSFiddle.

3 个答案:

答案 0 :(得分:3)

:nth-child 进一步将匹配的元素限制为其父元素的第n个子元素。没有CSS选择器匹配第n个具有类x 的元素。

对于给定的标记,您可以使用+组合器:

.visible ~ .visible ~ .visible ~ .visible ~ .visible {
  /*
   * matches .visible element with at least 4 previous .visible siblings
   */
  text-decoration: underline;
}
.visible ~ .visible ~ .visible ~ .visible ~ .visible ~ .visible {
  /*
   * matches .visible element with at least 5 previous .visible siblings
   */
  text-decoration: line-through;
}
<div class="ticket hidden">Hidden</div>
<div class="ticket hidden">Hidden</div>
<div class="ticket visible">Visible 1</div>
<div class="ticket visible">Visible 2</div>
<div class="ticket hidden">Hidden</div>
<div class="ticket hidden">Hidden</div>
<div class="ticket visible">Visible 3</div>
<div class="ticket visible">Visible 4</div>
<div class="ticket hidden">Hidden</div>
<div class="ticket hidden">Hidden</div>
<div class="ticket visible">Visible 5</div>
<div class="ticket visible">Visible 6</div>
<div class="ticket hidden">Hidden</div>
<div class="ticket hidden">Hidden</div>
<div class="ticket visible">Visible 7</div>
<div class="ticket visible">Visible 8</div>

答案 1 :(得分:1)

nth-child()不关心您要检查的课程。它总是计算DOM元素中的所有兄弟。

也许你想给:nth-of-type一个机会:developer.mozilla.org

也许最好的解决方案是使用一些jQuery并添加另一个类来追加underline样式

答案 2 :(得分:0)

您可以在visible课程的开头添加一个div,并为其提供nth-child http://jsfiddle.net/7uap9v21/3/

<div class="visible-holder">
<div class="visible ticket">BLA 4</div>
<div class="visible ticket">BLA 5</div>
<div class="visible ticket">BLA 6</div>
<div class="visible ticket">BLA 7</div>
<div class="visible ticket">BLA 8</div>
</div>