If you only need this, you really don’t need third-party libraries, you can use basic CSS yourself.
First you must understand how the selectors of CSS work.
For your need we need each row of the table to be of one color, so I’m going to assume that even lines are standard, white background, and odd ones will have their background altered.
For this, we will use the selector Nth-of-type which accepts numbers, literals Odd(unique) and Even(pair) and also expressions in the pattern an + b
, being a
the cycle of repetition, b
one offset and n
an indexed counter of 0
.
For example the expression 2n + 1
would consider the odd ones as well, ie 2 x 0 + 1 = 1
, 2 x 1 + 1 = 3
, etc..
Using this table as an example:
<table>
<thead>
<tr>
<th>Marca</th>
<th>Modelo</th>
</tr>
</thead>
<tbody>
<tr>
<td>Fiat</td>
<td>Punto</td>
</tr>
<tr>
<td>Volkswagen</td>
<td>Fusca</td>
</tr>
<tr>
<td>Ford</td>
<td>Fiesta</td>
</tr>
</tbody>
</table>
In our CSS we will use this:
tbody > tr:nth-of-type(odd) {
background-color: yellow;
}
This makes each line (<tr>
) odd has its color changed to yellow, but only those of the table body, that is, which are in <tbody>
.
See a full example with a little more CSS:
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
tbody > tr:nth-of-type(odd) {
background-color: yellow;
}
<table>
<thead>
<tr>
<th>Marca</th>
<th>Modelo</th>
</tr>
</thead>
<tbody>
<tr>
<td>Fiat</td>
<td>Punto</td>
</tr>
<tr>
<td>Volkswagen</td>
<td>Fusca</td>
</tr>
<tr>
<td>Ford</td>
<td>Fiesta</td>
</tr>
</tbody>
</table>
In this example we continue to put the yellow background for odd rows of the table body, but also include a solid and simple border.
perfect! I had not yet read anything about the selectors. I will definitely study about it. Thanks for the help!
– Luan Vicente