Home >Web Front-end >CSS Tutorial >How to Create Zebra Stripes in HTML Tables Using CSS and JavaScript?
How to Apply Alternate Table Row Colors Using CSS and JavaScript
In your HTML, you can use classes to apply alternate row colors, as you have demonstrated. However, you want to apply the styling to the table container itself and not to each individual row. CSS selectors provide a way to achieve this.
To make the table rows have zebra stripes, you can use the :nth-child(odd) pseudo-class. This selector targets every odd row within the table body (
). You can then apply styling to these odd rows, such as a different background color and text color.Using jQuery
If you prefer to use JavaScript, you can employ the jQuery library. With jQuery, you can select all odd rows in the table and apply the desired styling with the css() function.
Example HTML:
<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>
CSS:
tbody td { padding: 30px; } tbody tr:nth-child(odd) { background-color: #4C8BF5; color: #fff; }
jQuery:
$(document).ready(function() { $("tr:odd").css({ "background-color":"#000", "color":"#fff" }); });
With these methods, you can easily create alternate table row colors using CSS, ensuring a visually appealing presentation of your data.
The above is the detailed content of How to Create Zebra Stripes in HTML Tables Using CSS and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!