Create Zebra Striped Table with CSS



To create a table on a web page, we use the <table> element. It allows us to set the table row using the <tr> element. Within that, the <td> elements are used to place the data. A table can also be striped. Such striped tables have a different look for every alternative row. To set a property for evert alternative row, we will use the nth-child(even) property. Let us see how to create a zebra striped table with HTML and CSS.

Create a table

The <table> element is used to create a table. We have set three columns for our table. The headings are set using the <th> element. Three rows are created using the <tr> element −

<table>
   <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>BirthMonth</th>
   </tr>
   <tr>
      <td>Jack</td>
      <td>Roy</td>
      <td>January</td>
   </tr>
   <tr>
      <td>Steve</td>
      <td>Smith</td>
      <td>March</td>
   </tr>
   <tr>
      <td>Brandon</td>
      <td>Anderson</td>
      <td>February</td>
   </tr>
</table>

Style the table

We have set the width of the table using the width property −

table {
   border-collapse: collapse;
   border-spacing: 0;
   width: 100%;
   border: 1px solid #ddd;
}

Style the table header and cells

The th and td is styled like this. We have aligned it to the center using the text-align property with the left value −

th, td {
   font-weight: bold;
   font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
   font-size: 18px;
   text-align: left;
   padding: 16px;
}

Style alternative rows for a zebra striped table

The nth-child(even) can be used to style alternative rows −

tr:nth-child(even) {
   background-color: #8b8b8b;
   color: white;
}

Example

To create a zebra stripped table with CSS, the code is as follows −

<!DOCTYPE html>
<html>
<head>
   <style>
      table {
         border-collapse: collapse;
         border-spacing: 0;
         width: 100%;
         border: 1px solid #ddd;
      }
      th, td {
         font-weight: bold;
         font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
         font-size: 18px;
         text-align: left;
         padding: 16px;
      }
      tr:nth-child(even) {
         background-color: #8b8b8b;
         color: white;
      }
   </style>
</head>
<body>
   <h1>Zebra Striped Table Example</h1>
   <table>
      <tr>
         <th>First Name</th>
         <th>Last Name</th>
         <th>BirthMonth</th>
      </tr>
      <tr>
         <td>Jack</td>
         <td>Roy</td>
         <td>January</td>
      </tr>
      <tr>
         <td>Steve</td>
         <td>Smith</td>
         <td>March</td>
      </tr>
      <tr>
         <td>Brandon</td>
         <td>Anderson</td>
         <td>February</td>
      </tr>
   </table>
</body>
</html>
Updated on: 2023-12-14T12:40:49+05:30

716 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements