CSS Selector for nth range?

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>

Leave a Comment