Zin Yosrim
Zin Yosrim

Reputation: 1684

How to alternate in a table cell background color in each row and column

I'd like to format a CSS as shown in the image: In odd rows the first column cell and in even rows the second column cell should be formatted with a different background color.

example table

I know how to alternate a whole row or column like

tr {
border-top: 0px solid $input-border-col;
&:first-child {
    border-top: none;
}
&:nth-child(even) {background: #CCC;}
}

but haven't found a way how to alternate in each row

Upvotes: 2

Views: 5120

Answers (3)

Khalid T.
Khalid T.

Reputation: 10547

You could use the following rule:

tr {
    &:nth-child(odd) {
        >td {
            &:nth-child(odd) {
                background-color: red;
            }
            &:nth-child(even) {
                background-color: white;
            }
        }
    }
    &:nth-child(even) {
        >td {
            &:nth-child(odd) {
                background-color: white;
            }
            &:nth-child(even) {
                background-color: red;
            }
        }
    }
}

Upvotes: 1

caramba
caramba

Reputation: 22480

You can use odd and even CSS pseudo names.

Like this it does not matter how many <tr> or <td> your <table> will have.

td {
  padding: 20px;
  border: 1px solid black;
}

table tr:nth-child(odd) td:nth-child(odd),
table tr:nth-child(even) td:nth-child(even) {
    background: orange;
}
<table>
  <tr>
    <td>x</td>
    <td>x</td>
    <td>x</td>
    <td>x</td>
  </tr>
  <tr>
    <td>x</td>
    <td>x</td>
    <td>x</td>
    <td>x</td>
  </tr>
  <tr>
    <td>x</td>
    <td>x</td>
    <td>x</td>
    <td>x</td>
  </tr>
  <tr>
    <td>x</td>
    <td>x</td>
    <td>x</td>
    <td>x</td>
  </tr>
</table>

Upvotes: 7

Nenad Vracar
Nenad Vracar

Reputation: 122027

You can combine nth-child selector with first/last child to get desired result. So you can select all tr with 2n + 1 or odd rows and select first td and then select tr with 2n + 2 or even rows and select last td

td {
  padding: 20px;
  border: 1px solid black;
}

tr:nth-child(2n + 1) td:first-child,
tr:nth-child(2n + 2) td:last-child {
  background: #EA9999;
}
<table>
  <tr>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
  </tr>
</table>

Upvotes: 3

Related Questions