How to create a zebra striped table with CSS?

To create a zebra striped table with CSS, you can use the :nth-child selector to target specific table rows and apply alternating background colors. Here’s an example of how you can achieve this effect:

HTML:

<table class="zebra-table">
  <tr>
    <th>Header 1</th>
    <th>Header 2</th>
    <th>Header 3</th>
  </tr>
  <tr>
    <td>Row 1, Column 1</td>
    <td>Row 1, Column 2</td>
    <td>Row 1, Column 3</td>
  </tr>
  <tr>
    <td>Row 2, Column 1</td>
    <td>Row 2, Column 2</td>
    <td>Row 2, Column 3</td>
  </tr>
  <!-- Add more table rows here -->
</table>

CSS:

.zebra-table tr:nth-child(even) {
  background-color: #f2f2f2; /* Set the background color for even rows */
}

In this example, we have a simple HTML table with multiple rows. The zebra-table class is added to the table element for specificity. In the CSS, the tr:nth-child(even) selector targets every even row within the table and applies a background color of #f2f2f2. You can adjust the background color to your preference.

By using the :nth-child(even) selector, the background color is applied to every second row, creating a zebra striped effect. The odd rows will have the default background color, while the even rows will have the specified background color.

Feel free to customize the CSS to fit your design requirements, such as adjusting font colors, padding, borders, or any other styling properties for the table and its cells.

error: Content is protected !!