WordBear
WordBear

Reputation: 177

Modifying nth child for table cells

This CSS rule works fine:

.TabSymbols tr:nth-child(even) { background-color: #f2f2f2; }

Every other row has a background color.

Now imagine a table with four columns. Every table cell in the third and fourth column has the class "Date"...

<td class="Date">

The following style is applied to .Date:

.Date { background: #666; color: #fff; }

But here's the catch: I don't want every cell with class Date to have a background color. Rather, I want the styles to correspond with the first rule listed above. So the first two cells in every even-numbered row will have the background color #f2f2f2, while the last two cells will have the background #666. The odd-numbered rows will be a solid white, or whatever the table's background color is.

I tried these rules without success:

.TabSymbols tr:nth-child(even) td.Date { background-color: #666; }
.TabSymbols tr:nth-child(even).Date { background-color: #666; }

I also took a cue from this discussion and tried this:

tr td.Date:nth-child(2) { background-color: #666; color: #fff; }​

Maybe I could somehow use the col function with tr:nth?

Upvotes: 2

Views: 938

Answers (1)

Michael Coker
Michael Coker

Reputation: 53674

You can either apply the .Date background on tr:nth-child(odd) or tr:not(:nth-child(even))

.TabSymbols tr:nth-child(even) { background-color: #f2f2f2; }
/*.TabSymbols tr:nth-child(odd) .Date { background: #666; color: #fff; }*/
.TabSymbols tr:not(:nth-child(even)) .Date { background: #666; color: #fff; }
<table class="TabSymbols">
  <tr>
    <td class="Date">foo</td>
    <td>foo</td>
    <td>foo</td>
    <td>foo</td>
  </tr>
  <tr>
    <td>foo</td>
    <td>foo</td>
    <td class="Date">foo</td>
    <td class="Date">foo</td>
  </tr>
  <tr>
    <td>foo</td>
    <td>foo</td>
    <td class="Date">foo</td>
    <td>foo</td>
  </tr>
  <tr>
    <td>foo</td>
    <td class="Date">foo</td>
    <td>foo</td>
    <td>foo</td>
  </tr>
</table>

Upvotes: 2

Related Questions