第 n 个范围的 CSS 选择器?

标签 css css-selectors

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

.myTableRow td:nth-child(?){
  background-color: #FFFFCC;
}

所以它适用于 td2~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>

最佳答案

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

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

这更清楚一些,因为它包含了您范围内的数字(24),而不必从末尾倒数。

它也更加健壮,因为您不必考虑元素的总数。

为了澄清:

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

示例:

#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;
}
<div id="nn">
    <div></div>    
    <div></div>    
    <div></div>    
    <div></div>    
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>

关于第 n 个范围的 CSS 选择器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59177343/

相关文章:

javascript - Css 文件未检测到 html 中数据主题的更新

dom - 在 Prototype 中使用 $$ 是不是不好?

java - 如何通过Selenium找到具有随机id属性的元素

javascript - 更改 div 元素的背景颜色循环淡入淡出

javascript - 无法让 fadeIn() 在 addClass 上工作

html - 我怎样才能去掉顶部多余的空白区域?

javascript - jQuery CSS 'or' 选择器

javascript - 如果需要,删除 CSS 选择器及其相关属性

html - div ID 中的多个无序列表

html - 无需调整 Logo 大小的粘性顶部导航栏