第n个范围的CSS选择器?

QFD*_*Dev 24 css css-selectors

我如何调整下面的CSS选择器:

.myTableRow td:nth-child(?){
  background-color: #FFFFCC;
}
Run Code Online (Sandbox Code Playgroud)

所以它适用于td列2-4?

<table>
  <tr class="myTableRow">
    <td>column 1</td>
    <td>column 2</td>
    <td>column 3</td>
    <td>column 4</td>
    <td>column 5</td>
  </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

JLR*_*she 45

您可以使用的另一种方法是:

.myTableRow td:nth-child(n+2):nth-child(-n+4){
    background-color: #FFFFCC;
}
Run Code Online (Sandbox Code Playgroud)

这有点清楚,因为它包含您范围内的数字(24),而不必从末尾向后计数.

它也更健壮,因为您不必考虑所有项目的总数.

为了澄清:

:nth-child(n+X)     /* all children from the Xth position onward */
:nth-child(-n+x)    /* all children up to the Xth position       */
Run Code Online (Sandbox Code Playgroud)

例:

#nn div {
    width: 40px;
    height: 40px;
    background-color: black;
    display: inline-block;
    margin-right: 10px;
}

#nn div:nth-child(n+3):nth-child(-n+6) {
    background-color: blue;
}
Run Code Online (Sandbox Code Playgroud)
<div id="nn">
    <div></div>    
    <div></div>    
    <div></div>    
    <div></div>    
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 这似乎更具可读性.谢谢 (4认同)
  • 该解决方案更加干净,不易出错,并且更适合目的。该示例有助于可视化解决方案。这应该是公认的答案。 (2认同)

Bol*_*ock 28

你将不能用一个单独做到这一点:nth-child()- 你需要链接至少一个其他这样的伪类.例如,的组合:nth-child():nth-last-child()(该n+2位意味着开始从第二子分别计数向前和向后):

.myTableRow td:nth-child(n+2):nth-last-child(n+2){
background-color: #FFFFCC;
}
Run Code Online (Sandbox Code Playgroud)

或者,不要使用公式,只需排除:first-child:last-child:

.myTableRow td:not(:first-child):not(:last-child){
background-color: #FFFFCC;
}
Run Code Online (Sandbox Code Playgroud)