How to style alternating table rows with different background colors in CSS

Arif Billah Babu

         

  CSS



Image not found!!

You can style alternating table rows with different background colors in CSS using the :nth-child pseudo-class. Here's an example:

css
/* Apply styles to even rows */ tr:nth-child(even) { background-color: #f2f2f2; } /* Apply styles to odd rows */ tr:nth-child(odd) { background-color: #ffffff; }

In this example, the :nth-child(even) selector targets every even row of the table, while :nth-child(odd) targets every odd row. You can adjust the background colors to your preference by changing the hexadecimal color codes.

Here's an example of how you can incorporate these styles into your HTML:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> /* Apply styles to even rows */ tr:nth-child(even) { background-color: #f2f2f2; } /* Apply styles to odd rows */ tr:nth-child(odd) { background-color: #ffffff; } </style> <title>Alternating Table Rows</title> </head> <body> <table> <tr> <td>Row 1, Cell 1</td> <td>Row 1, Cell 2</td> </tr> <tr> <td>Row 2, Cell 1</td> <td>Row 2, Cell 2</td> </tr> <tr> <td>Row 3, Cell 1</td> <td>Row 3, Cell 2</td> </tr> <!-- Add more rows as needed --> </table> </body> </html>

This will give you a table with alternating background colors for each row. Adjust the colors and styles as needed for your specific design.