第 n 个范围的 CSS 选择器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15639247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 22:11:23  来源:igfitidea点击:

CSS Selector for nth range?

csscss-selectors

提问by QFDev

How can I adapt the CSS selector below:

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

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

so it applies to td columns 2-4?

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

回答by JLRishe

One more approach you could use is:

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

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

This is a little clearer because it includes the numbers in your range (2and 4) instead of having to count backwards from the end.

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

It's also a bit more robust because you don't have to consider the total number of items there are.

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

For clarification:

为了澄清:

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

Example:

例子:

#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>

回答by BoltClock

You won't be able to do this with a single :nth-child()— you'll need to chain at least one other such pseudo-class. For example, a combination of :nth-child()and :nth-last-child()(the n+2bit means start counting forward and backward respectively from the 2nd child):

您将无法使用单个来执行此操作:nth-child()— 您需要链接至少一个其他此类伪类。例如,的组合:nth-child():nth-last-child()(该n+2位装置开始从第二子分别计数向前和向后):

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

Alternatively, instead of making use of a formula, simply exclude :first-childand :last-child:

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

.myTableRow td:not(:first-child):not(:last-child){
background-color: #FFFFCC;
}

回答by Sky Yip

If you want to select elements 2 through 4, here's how you can do it:

如果您想选择元素 2 到 4,您可以这样做:

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

Remind that the selector chain sequence should be from greatest to least. Safari has a bug that prevents this technique from working.

提醒选择器链的顺序应该是从大到小。Safari 有一个错误,阻止此技术工作。