Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (20.3k points)

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 the table. When I use class for a table than this applies to 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?

1 Answer

0 votes
by (40.7k points)

You can try using this code:

 $(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>

If you are working on pure CSS, then you can do as follows:

tr:nth-child(even) {

    background-color: #000000;

}

Note 1: Here, nth-child is nothing but a CSS selector i.e. a pseudo-selector.

Note 2: No support in IE 8.

Or, if you are working on jQuery then do this:

$(document).ready(function()

{

  $("tr:even").css("background-color", "#000000");

});

Related questions

Browse Categories

...