Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS selector for selecting an alternating element group

I have an HTML table that I want to highlight alternating groups of 3 rows such that rows 0-3 are highlighted, rows 4-6 are not, rows 7-9 are highlighted, etc.

The best solution I've come up with so far is:

tr:nth-child(6n + 1),
tr:nth-child(6n + 2),
tr:nth-child(6n + 3) {
   background-color:#eee;
}

Is is possible to condense these selectors into a single selector?

like image 293
asponge Avatar asked Oct 22 '22 11:10

asponge


2 Answers

Yes, its possible in a single selector (but is it best???)

If doing it in groups of ten (as your comment says is your ultimate goal) it may not be worth doing as opposed to having the ten individual selectors, as the individual selectors will probably be more clear.

Groups of Three (see fiddle)

tr:not(:nth-child(6n+4)):not(:nth-child(6n+5)):not(:nth-child(6n+6)) {
    background-color: #eee;
}

Groups of Ten (see fiddle)

tr:not(:nth-child(20n+11)):not(:nth-child(20n+12)):not(:nth-child(20n+13)):not(:nth-child(20n+14)):not(:nth-child(20n+15)):not(:nth-child(20n+16)):not(:nth-child(20n+17)):not(:nth-child(20n+18)):not(:nth-child(20n+19)):not(:nth-child(20n+20)) {
    background-color: #eee;
}

This obviously does not eliminate your copy/paste of code issue you hoped to avoid, and questionable as to whether it qualifies as "condensed." However, it is reduced to a single selector.

like image 148
ScottS Avatar answered Oct 27 '22 09:10

ScottS


If your rows are being styled this way because there is a relationship between them, then grouping them using the <tbody> element is appropriate here and would trim down your selector.

http://codepen.io/cimmanon/pen/KqoCs

tbody:nth-child(odd) {
  background: #CCC;
}

<table>
    <tbody>
        <tr>
            <td rowspan="3"></td>
            <td>a</td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td>b</td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td>c</td>
            <td></td>
            <td></td>
        </tr>
    </tbody>

    <tbody>
        <tr>
            <td rowspan="3"></td>
            <td>a</td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td>b</td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td>c</td>
            <td></td>
            <td></td>
        </tr>
    </tbody>

    <tbody>
        <tr>
            <td rowspan="3"></td>
            <td>a</td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td>b</td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td>c</td>
            <td></td>
            <td></td>
        </tr>
    </tbody>
</table>
like image 43
cimmanon Avatar answered Oct 27 '22 09:10

cimmanon