Home >Web Front-end >CSS Tutorial >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:
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.
With jQuery, you can select and style the odd-numbered rows dynamically:
$(document).ready(function() { $("tr:odd").css("background-color", "#CCCCCC"); });
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.
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!