Apply style to alternate tr of table using CSS and jQuery




  • In this article we will see how to apply style to alternate tr of a table.
  • We can achieve this using either CSS of by jQuery.


Using CSS :

CSS provides a pseudo selector which selects alternate tr of table and applies specified properties.


:nth-child() is the selector which works for us. 


This selector is not supported in all browser.


Example :



<html>
<head>
<style type="text/css"">
tr:nth-child(even)
{
color:red;
}
tr:nth-child(odd)
{
color:green;
}
</style>
</head>
<body>
<table border="1">
    <tr><td>jQuery</td><td>Amazing</td></tr>
    <tr><td>CSS</td><td>Beautiful</td></tr>
    <tr><td>MVC3</td><td>Creative</td></tr>
    <tr><td>CSS3</td><td>Wonderful</td></tr>
</table>
</body>
</html>

Demo :




In the above example, we have created a table element. We have used :nth-child(even) selector to select all the even tr of table and applied css to it. We have done same thing for odd tr's.


Using jQuery :


We can also use jQuery to apply style to alternate tr's of the table. In jQuery we have even and odd selector to select the respective tr's of table. We will define CSS classes which we will add using addClass() method.


Example :



<html>
<head>
<style type="text/css"">
.evenTR
{
    color:Red;
}
.oddTR
{
    color:Green;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> 
</script>
<script type="text/javascript">
    $(document).ready(function () {
        $("tr:even").addClass("evenTR");
        $("tr:odd").addClass("oddTR");
    });
</script>
</head>
<body>
<table border="1">
    <tr><td>jQuery</td><td>Amazing</td></tr>
    <tr><td>CSS</td><td>Beautiful</td></tr>
    <tr><td>MVC3</td><td>Creative</td></tr>
    <tr><td>CSS3</td><td>Wonderful</td></tr>
</table>
</body>
</html>

Demo :




In the above demo we have achieved same what we achieved using CSS. In the above example, we have created two CSS classes one for all odd tr's and one for all even tr's. On document ready we selected the even tr's using even selector in jQuery and applied CSS by adding the CSS class using addClass() method.


So, we could achieve the alternate tr styling using both CSS and jQuery.

1 comments:

  1. This is a very nice article on css tables i like your article.

    ReplyDelete