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.
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;
}
@Eric's answer is exactly right - but if you want to easily extend this to groups of 3, 4, 5, etc, and you're using Sass, here's the code (if you want more groups, just increase $largestGroupSize
):
.table-with-grouped-rows {
// generate styles for .groups-of-2, .groups-of-3, etc.
$largestGroupSize: 6;
@for $groupNumPerColor from 2 through $largestGroupSize{
$totalGroupNum: $groupNumPerColor * 2;
&.groups-of-#{$groupNumPerColor} {
$start: $totalGroupNum - 1;
$end: $groupNumPerColor;
@for $primaryBgIndex from $start through $end {
$nthString: #{$totalGroupNum}n - #{$primaryBgIndex};
> tbody > tr:nth-of-type(#{$nthString}) > td {
background-color: $white;
}
}
$start: $groupNumPerColor - 1;
$end: 0;
@for $alternateBgIndex from $start through $end {
$nthString: #{$totalGroupNum}n - #{$alternateBgIndex};
> tbody > tr:nth-of-type(#{$nthString}) > td {
background-color: $light-gray;
}
}
}
}
}
And then in your markup, on the <table>
element, you'd simply add the classes table-with-grouped-rows
and groups-of-{n}
. For example, if you want a table with groups of 3, you'd write:
<table class="table-with-grouped-rows groups-of-3">
Boom.