Sk1X1
Sk1X1

Reputation: 1373

Different color for rows in table

It's possible to create something like this only through table CSS style? I can create different color for even and odd rows, but I would like to create this (just the colors):

example

Upvotes: 0

Views: 221

Answers (1)

DRD
DRD

Reputation: 5813

Assuming that the number of rows is constant, you can use nth-of-type, nth-last-of-type, or nth-child selectors plus the formulae, to make the coloring work. This example also requires to play with selector specificity by placing rule sets in a particular order: http://jsfiddle.net/se4Lwt1y/.

HTML:

<table>
    <tr><td>Row 1</td></tr>
    <tr><td>Row 2</td></tr>
    <tr><td>Row 3</td></tr>
    <tr><td>Row 4</td></tr>
    <tr><td>Row 5</td></tr>
    <tr><td>Row 6</td></tr>
    <tr><td>Row 7</td></tr>
    <tr><td>Row 8</td></tr>
    <tr><td>Row 9</td></tr>
    <tr><td>Row 10</td></tr>
    <tr><td>Row 11</td></tr>
    <tr><td>Row 12</td></tr>
    <tr><td>Row 13</td></tr>
    <tr><td>Row 14</td></tr>
    <tr><td>Row 15</td></tr>
    <tr><td>Row 16</td></tr>
    <tr><td>Row 17</td></tr>
    <tr><td>Row 18</td></tr>
    <tr><td>Row 19</td></tr>
    <tr><td>Row 20</td></tr>
    <tr><td>Row 21</td></tr>
</table>

CSS:

table {
    width: 100%;
}

table tr:nth-of-type(-n + 11) {
    background-color: hsla(60, 70%, 70%, 1);
}

table tr:nth-of-type(-n + 3) {
    background-color: hsla(0, 0%, 70%, 1);
}

table tr:nth-last-of-type(-n + 11) {
    background-color: hsla(200, 50%, 70%, 1);
}

table tr:nth-last-of-type(-n + 4) {
    background-color: hsla(200, 50%, 60%, 1);
}

Upvotes: 1

Related Questions