Skip to content Skip to sidebar Skip to footer

Alternating Table Row Color With The First Row A Different Color

I want to make a table where the header is green and then the rows alternate between different styles. How can I style the first row's color as well as having the others alternate?

Solution 1:

You just have to place the first-child rule after the rest, so it overrides them.

.butikHeader tr:nth-child(even) {
    background:#FFF;
    border:0px;
    color:#000;
}
.butikHeader tr:nth-child(odd) {
    background:#DFE7C0;
}
.butikHeader tr:first-child {
    background:#8AB512;
    color:#FFF;
}

Solution 2:

Use thead and tbody

thead tr {
  background:#8AB512;
    color:#FFF;
}

tbody tr:nth-child(even) {
    background:#FFF;
    border:0px;
    color:#000;
}

tbody tr:nth-child(odd) {
    background:#DFE7C0;
}
<table>
 <thead>
  <tr>
     <th>Month</th>
     <th>Savings</th>
  </tr>
 </thead>
 <tbody>
  <tr>
     <td>Sum</td>
     <td>$180</td>
  </tr>
 
  <tr>
     <td>January</td>
     <td>$100</td>
  </tr>
  <tr>
     <td>February</td>
     <td>$80</td>
  </tr>
 </tbody>
</table>

Solution 3:

Errrm your code all works. I'd guess something that's not in your sample code is affecting it.

Try adding !important after each css statement eg:

.butikHeader tr:nth-child(odd) {
    background:#DFE7C0 !important;
}

To test the theory. I'm not a fan of using !important generally by the way, but that's another story.

Also I would suggest you split your top row into a thead element and subsequent ones into a tbody statement, but I guess again, that's another story.


Post a Comment for "Alternating Table Row Color With The First Row A Different Color"