Change row color every x rows in HTML table

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

Just for the sake of explanation, this is what it might look like if every two lines changed : JSFiddle

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 the for class to tr

be tagged, but I want a more general way, perhaps using a selector nth-child

or something.

Does anyone know of a simple way to do this, perhaps with a variable number of changing lines (e.g. every 2 lines, 3 lines, 4 lines, ...)? As I said, I would like to avoid adding the class names, because the table will probably be dynamically generated and therefore I most likely cannot change this code.

+3


source to share


4 answers


You can set colors using nth-child like this:

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

      



For more than two different options, you use the formula (a + b), where a represents the size of the loop, n is the counter (starts at 0), and b is the offset value. Here we specify the 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;}

      

+5


source


You are right with nth-child

. Think only in multiples / groups of 4:



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

      

+4


source


You can use an expression for nth-child

tr as shown below:

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

      

Demo here

0


source


Example of the above code

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

      

4n+1

s n = 0

: 4 * 0 + 1 = 1
4n+1

s n = 1

: 4 * 1 + 1 = 5
4n+1

s n = 2

: 4 * 2 + 1 = 9
4n+1

s n = 3

: 4 * 3 + 1 = 13
4n+1

s n = 4

: 4 * 4 + 1 = 17
4n+1

s n = 5

: 4 * 5 + 1 = 21

Same meaning for 4n+2

:

4n+2

s n = 0

: 4 * 0 + 2 = 2
4n+2

s n = 1

: 4 * 1 + 2 = 6
4n+2

s n = 2

: 4 * 2 + 2 = 10
4n+2

s n = 3

: 4 * 3 + 2 = 14
4n+2

s n = 4

: 4 * 4 + 2 = 18
4n+2

s n = 5

: 4 * 5 + 2 = 22

Note: n

always starts with 0

default.

0


source







All Articles