user1943020
user1943020

Reputation:

Why does my alternate row background color not work for my table?

I am using the following CSS and HTML:

table.grid tbody tr:nth-child(odd) {
  background: #888;
}


<table class="form grid">
   <tbody>
      <tr>
         <td>xx</td>
      </tr>
      <tr>
         <td>xx</td>
      </tr>
      <tr>
         <td>xx</td>
      </tr>
      <tr>
         <td>xx</td>
      </tr>
   </tbody>
</table>

The table shows up fine but there is no different background color shading for the rows. Am I missing something?

Upvotes: 1

Views: 2476

Answers (2)

Jwit
Jwit

Reputation: 156

This question has been answered several times before. There are known compatibility issues with CSS3 and IE which are known to break the nth-child selector. You may have to use JQuery to do it instead. Here is some info which may help

Alternate table row color using CSS?

Upvotes: 0

Ryan Williams
Ryan Williams

Reputation: 705

Try adjusting your CSS selector to table.grid tbody tr:nth-child(odd) td {.

This may help in case you have other CSS in your document affecting the background property of td elements, while also allowing you to do column-specific styling (e.g. for sorting). I find this preferable to applying the background property to tr elements.

Here's a Fiddle demonstrating that this should indeed work with your CSS unless something else in your CSS is affecting it.

Upvotes: 1

Related Questions