How do I style alternating rows in a table using CSS?
Antek N
antek n profile pic

Styling alternating rows in a table using CSS involves applying styles to specific table rows to create a visual distinction between them. This helps improve readability and makes it easier for users to navigate through the table. Here's a step-by-step guide on how to achieve this: 1. HTML Markup: Start by creating the HTML structure for your table. Here's an example with a basic table structure:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  <table>
     <thead>
       <tr>
         <th>Header 1</th>
         <th>Header 2</th>
         <th>Header 3</th>
         <!-- Add more table headers if needed -->
       </tr>
     </thead>
     <tbody>
       <tr>
         <td>Row 1, Column 1</td>
         <td>Row 1, Column 2</td>
         <td>Row 1, Column 3</td>
         <!-- Add more table cells and rows if needed -->
       </tr>
       <tr>
         <td>Row 2, Column 1</td>
         <td>Row 2, Column 2</td>
         <td>Row 2, Column 3</td>
       </tr>
       <!-- Add more rows as needed -->
     </tbody>
   </table>
   

2. CSS Styling: Apply CSS styles to alternate rows in the table using the:nth-child selector. The:nth-child selector allows you to target specific elements based on their position in a parent container. In this case, we'll use it to target the odd and even rows. Here's an example:

1
2
3
4
5
6
7
8
9
 table {
     width: 100%;
     border-collapse: collapse;
   }

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

In this example, we set the width of the table to100% and collapse the table borders withborder-collapse: collapse. Thetr:nth-child(odd) selector targets the odd rows (1st, 3rd, 5th, etc.) within the element and applies a background color of#f2f2f2. This creates a visual distinction for alternating rows. 3. Additional Styling: Customize the styling as per your design requirements. You can apply different styles to alternating rows, such as changing the text color, font weight, or adding borders. For example:

1
2
3
4
5
6
7
 tr:nth-child(odd) {
     background-color: #f2f2f2;
     color: #333;
     font-weight: bold;
     border-bottom: 1px solid #ddd;
   }
   

In this example, we set the text color to#333, the font weight tobold, and add a bottom border of1px solid #ddd to the odd rows. 4. Responsive Considerations: When styling alternating rows, consider how your design will adapt to different screen sizes and devices. Ensure that the styles you apply to the alternating rows do not interfere with the overall responsiveness and legibility of the table. By following these steps and customizing the CSS styles within thetr:nth-child(odd) selector, you can style alternating rows in a table using CSS. The applied styles create a visual distinction between the rows, enhancing the readability and overall design of your table.