Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate table row color using CSS?

I am using a table with alternate row color with this.

tr.d0 td {    background-color: #CC9999;    color: black;  }  tr.d1 td {    background-color: #9999CC;    color: black;  }
<table>    <tr class="d0">      <td>One</td>      <td>one</td>    </tr>    <tr class="d1">      <td>Two</td>      <td>two</td>    </tr>  </table>

Here I am using class for tr, but I want to use only for table. When I use class for table than this apply on tr alternative.

Can I write my HTML like this using CSS?

<table class="alternate_color">     <tr><td>One</td><td>one</td></tr>     <tr><td>Two</td><td>two</td></tr>     </table> 

How can I make the rows have "zebra stripes" using CSS?

like image 242
Kali Charan Rajput Avatar asked Jun 21 '10 11:06

Kali Charan Rajput


People also ask

How do I make every other row shaded in CSS?

You can use this css to select every other paragraph by changing the css to "p:nth-child(even)", or list items: li:nth-child(even), etc. Change "even" to "odd" if you want the shading to affect odd rows.


1 Answers

$(document).ready(function() {   $("tr:odd").css({     "background-color":"#000",     "color":"#fff"}); });
tbody td{   padding: 30px; }  tbody tr:nth-child(odd){   background-color: #4C8BF5;   color: #fff; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table border="1"> <tbody> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> </tr> <tr> <td>5</td> <td>6</td> <td>7</td> <td>8</td> </tr> <tr> <td>9</td> <td>10</td> <td>11</td> <td>13</td> </tr> </tbody> </table>

There is a CSS selector, really a pseudo-selector, called nth-child. In pure CSS you can do the following:

tr:nth-child(even)     background-color: #000000; } 

Note: No support in IE 8.

Or, if you have jQuery:

$(document).ready(function() {     $("tr:even").css("background-color", "#000000"); }); 
like image 93
Russell Dias Avatar answered Sep 16 '22 14:09

Russell Dias