How can I adapt the CSS selector below:
.myTableRow td:nth-child(?){ background-color: #FFFFCC; }
so it applies to td
columns 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>
The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.
The syntax for selecting the first n number of elements is a bit counter-intuitive. You start with -n , plus the positive number of elements you want to select. For example, li:nth-child(-n+3) will select the first 3 li elements.
The :nth-of-type selector allows you select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.
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>
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With