Lesson 104: Zebra Striping

Estimated Length: 20min | Difficulty: Beginner

In this lesson, we will be going over how to create a zebra striping effect into coded tables using jQuery. The "zebra" striping helps add more contrast to the different rows in your table to make it easier to read for the user. Also, it looks more pleasing to the eye than a plain table.

Example:

Col-1 Col-2 Col-3 Col-4 Col-5
Data-1 Data-2 Data-3 Data-4 Data-5
Data-1 Data-2 Data-3 Data-4 Data-5
Data-1 Data-2 Data-3 Data-4 Data-5

HTML

Before anything else, you need to have a basic table to be able to add the effect to.

The basic layout for a table would be:

<table>

<thead>

<tr>

<th>Col-1</th>

<th>Col-2</th>

<th>Col-3</th>

</tr>

</thead>

<tbody>

<tr>

<td>Data-1</td>

<td>Data-2</td>

<td>Data-3</td>

</tr>

<tr>

<td>Data-1</td>

<td>Data-2</td>

<td>Data-3</td>

</tr>

<tr>

<td>Data-1</td>

<td>Data-2</td>

<td>Data-3</td>

</tr>

</tbody>

</table>

Now that you have the basic table set up, add an id to the <table> tag to call the zebra styles to. We just named the id "zebra"

CSS

Here are some basic styles that we added to the table and other table elements. Feel free to adjust these to better fit your website.

table{border-collapse:collapse; font-size:12px; width:480px;}

th{border-bottom:2px solid #A3A3A3; color:#303030; font-size:14px; text-align:left; padding:5px;}

td{padding:5px;}

jQuery

The jQuery in this lesson is used to add in the zebra striping effect. It selects the table, the table body, and the (even) table rows only. If you would like, you could also select the odd table rows by changing "tr:even" to "tr:odd". Then we choose what we want the background color to be.

<script>

$(document).ready(function(){ //document is ready

$('#zebra tbody tr:even').css('background-color','#ddd'); //select all even tr of the tbody within the selected element and add css background color to the even tr

}); //end function

</script>

Once you have this code added, you should have a slick zebra effect added to your basic table.

See it all together

See the Pen Zebra Striping by Rachel Hutchings (@imracheljoy) on CodePen.