Pieter VDE
Pieter VDE

Reputation: 2235

Alter row color every x rows on a HTML table

As the question title says, I would like to alter the row colors in a table every x rows. Not every row, but every x rows.

Just for the sake of explaining, this is what it could look like when altering every 2 rows: JSFiddle

The HTML is just a regular table, something like this:

<table>
    ...
    <tr>
        <td>content</td>
        <td>more content</td>
    </tr>
    ...
</table>

In the example I'm using a class for the tr's that should be marked, but I want a more generic way, possibly making use of the nth-child selector or something along that way.

Does anybody know of a simple way to do this, possibly with a variable number of altering rows (e.g. every 2 rows, 3 rows, 4 rows,... )? As said, I would like to avoid adding class names because the table would probably be dynamically generated and thus I am most likely not able to alter that code.

Upvotes: 4

Views: 6818

Answers (4)

Suraj Rawat
Suraj Rawat

Reputation: 3763

Example of the above code

tr:nth-child(4n+1), tr:nth-child(4n+2) { 
    background-color: gray;
}

4n+1 with n = 0: 4 * 0 + 1 = 1
4n+1 with n = 1: 4 * 1 + 1 = 5
4n+1 with n = 2: 4 * 2 + 1 = 9
4n+1 with n = 3: 4 * 3 + 1 = 13
4n+1 with n = 4: 4 * 4 + 1 = 17
4n+1 with n = 5: 4 * 5 + 1 = 21

The same counts for 4n+2:

4n+2 with n = 0: 4 * 0 + 2 = 2
4n+2 with n = 1: 4 * 1 + 2 = 6
4n+2 with n = 2: 4 * 2 + 2 = 10
4n+2 with n = 3: 4 * 3 + 2 = 14
4n+2 with n = 4: 4 * 4 + 2 = 18
4n+2 with n = 5: 4 * 5 + 2 = 22

Note: n always starts at 0 by default.

Upvotes: 3

sri
sri

Reputation: 338

You could use an expression for the nth-child of tr as shown below:

tr:nth-child(an+b) {    //a and b can be changed to your requirement
    background-color: #AAA;
}

Demo here

Upvotes: 0

Cory Carter
Cory Carter

Reputation: 144

You're right with nth-child. Just think in multiples/groups of 4:

tr:nth-child(4n+1), tr:nth-child(4n+2) {
    background-color: yellow;
    /* possibly other styles */
}

Upvotes: 5

entreprenerds
entreprenerds

Reputation: 1027

You can set colours using nth-child like this:

tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}

For more than 2 different options, you use the formula (an + b) where a represents a cycle size, n is a counter (starts at 0), and b is an offset value. Here, we specify a background color for all tr elements whose index is a multiple of 3:

tr:nth-child(3n+0) {background:#999;}
tr:nth-child(3n+1) {background:#CCC;}
tr:nth-child(3n+2) {background:#FFF;}

Upvotes: 11

Related Questions