Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
573 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...