CSS Selector for nth range?
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+2
bit means start counting forward and backward respectively from the 2nd child):
.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-child
and :last-child
:
.myTableRow td:not(:first-child):not(:last-child){
background-color: #FFFFCC;
}
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 (2
and 4
) instead of having to count backwards from the end.
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>