In the world of web development, tables are an essential tool for organizing and presenting data. However, reading an extensive table can sometimes be challenging due to the lack of contrast between rows. Fortunately, CSS offers a simple solution to improve readability: highlighting even rows with a different color. In this tutorial, I'll show you how to do this efficiently using CSS.
Before diving into the code, let’s briefly discuss why highlighting even rows is beneficial. The primary reason is enhanced readability. By using alternating colors for rows, you help users follow the information more easily and clearly, especially in lengthy tables.
First, you need to have a table in your HTML. Here’s a basic example of a table:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Table Example</title> <link rel="stylesheet" href="styles.css"> </head> <body> <table> <thead> <tr> <th>Name</th> <th>Age</th> <th>City</th> </tr> </thead> <tbody> <tr> <td>Ana</td> <td>28</td> <td>Madrid</td> </tr> <tr> <td>Pedro</td> <td>34</td> <td>Barcelona</td> </tr> <tr> <td>Laura</td> <td>22</td> <td>Valencia</td> </tr> <!-- More rows here --> </tbody> </table> </body> </html>
Now that we have the basic table structure, let’s add styling to highlight the even rows. We’ll use the CSS nth-child pseudo-class for this.
In your CSS file (styles.css), add the following code:
/* General styles for the table */ table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } /* Style for even rows */ tbody tr:nth-child(even) { background-color: #f2f2f2; }
You can adjust the background color to suit your preferences by changing the background-color value. For instance, if you prefer a darker color for even rows, you can use a different hexadecimal color code.
tbody tr:nth-child(even) { background-color: #e0e0e0; /* Darker gray */ }
Highlighting even rows in a table with CSS is a simple yet effective technique to enhance the readability and appearance of your tables. With the provided code, you can apply this technique to your web projects and customize it according to your needs.
I hope this tutorial has been helpful.
Thank you for reading, and happy coding!
Page loaded in 36.04 ms