I need to make every two rows of my table grey and I would prefer to use nth-child if possible.
I've messed around with Chris Coyier's nth-child tester but still can't get it.
I need the following formula:
1,2 - grey 3,4 - white 5,6 - grey 7,8 - white 9,10 - grey
and so on. I'd prefer not to put a class in the html as I'm sure that's going to be a suggestion from some. If there is a way to pull this off with nth-child, that's what I'm looking for.
Use the querySelector() method to get the nth child of an element, e.g. document. querySelector('#parent :nth-child(3)') . The :nth-child pseudo class returns the element that matches the provided position.
Definition and UsageThe :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+2) will select the first 2 li elements.
Realize that you are doing groups of 4, then you can see that you can have every 4th element and every 4th element minus one being white, then every 4th element minus two, or every 4th element minus 3 being grey.
So, you'd use 4n
and 4n-1
, then 4n-2
and 4n-3
:
div:nth-child(4n), div:nth-child(4n-1) { background: red; } div:nth-child(4n-2), div:nth-child(4n-3) { background: blue; }
That code isn't precise to your case, I wrote it for a jsFiddle proof-of-concept.
NB disclaimer: Keep in mind that nth-child
does not work in IE8. Typical issue, of course.
Here's what I'm using to right-align the first column of each table.
table td:nth-child(2n-1) { align: right; text-align: right; }
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