Home >Web Front-end >CSS Tutorial >How Can I Use CSS and jQuery to Create Alternating Row Colors in HTML Tables?

How Can I Use CSS and jQuery to Create Alternating Row Colors in HTML Tables?

Barbara Streisand
Barbara StreisandOriginal
2024-12-27 08:59:14751browse

How Can I Use CSS and jQuery to Create Alternating Row Colors in HTML Tables?

Using CSS to Create Alternate Table Row Colors

Alternating table row colors enhance the visual appeal and usability of HTML tables, making them easier to read. Here's how you can achieve this using CSS:

  • Using Table Class:

You can assign a class to the table and apply styles to the table rows within that class:

.alternate_color tr:nth-child(odd) {
  background-color: #CCCCCC;
}

This will alternate the background color of odd-numbered rows.

  • Using jQuery:

With jQuery, you can select and style the odd-numbered rows dynamically:

$(document).ready(function() {
  $("tr:odd").css("background-color", "#CCCCCC");
});
  • nth-child:

Directly within the CSS stylesheet, you can use the nth-child selector to target every other row:

tbody tr:nth-child(odd) {
  background-color: #CCCCCC;
}

This ensures that only the odd-numbered rows will have the alternate background color.

  • Example HTML:

Here's an HTML example using the above methods:

<table class="alternate_color">
  <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>

By applying the appropriate CSS, you can easily create zebra stripes in your table, improving its readability and aesthetics.

The above is the detailed content of How Can I Use CSS and jQuery to Create Alternating Row Colors in HTML Tables?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn