Search code examples
htmlcsscss-selectorscss-tables

nth-child doesnt apply background-color correctly in the table


N-th child only applies the background-color to the 2nd child but doesnt continue. Take a look: https://snipboard.io/fnDY0r.jpg Any ideas? My HTML-table looks like this (sorry for the german) :

<table class="Tabellen" id="Oeffnungszeiten">
    <caption>Aktuelle Öffnungszeiten (Frühling/Sommer 2020) </caption>
    <thead>
        <tr>
            <th>Wochentag</th>
            <th>Uhrzeit</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Montag</td>
            <td>09.00 - 18.00 </td>
        </tr>
        <tr>
            <td>Dienstag</td>
            <td>09.00 - 18.00 </td>
        </tr>
        <tr>
            <td>Mittwoch</td>
            <td>09.00 - 17.00 </td>
        </tr>
        <tr>
            <td>Donnerstag</td>
            <td>09.00 - 20.00 </td>
        </tr>
        <tr>
            <td>Freitag</td>
            <td>08.00 - 20.00 </td>
        </tr>
        <tr>    
            <td>Samstag</td>
            <td>08.00 - 20.00 </td>
        </tr>
        <tr>
            <td>Sonntag</td>
            <td>10.00 - 20.00 </td>
        </tr>
    </tbody>
</table>

My CSS:

tr:nth-child(2) {
    background-color: red;
}

Solution

  • If you want to add background-color for every 2nd child (every even child: 2, 4, 6...), you need to use nth-child(even)

    Check out this snippet of even, odd selectors.