jQuery: Styling Large Data Tables with Less Code

For those who have worked with tables you know how much of a pain it can be to style it just right. In this article I’ll share with you how I get the job done quickly using jQuery and a bit of CSS class styles. Good table structure is key to great design. With it you have a lot of options in the way you present your table. Use the appropriate <th>, <tbody>, and other tags correctly. The result of this demo can be seen here. At the end of this post you can download the source code.

HTML Structure

Here’s the HTML:

<table>
<thead>
<tr>
<th>Books for Sale</th>
<th>Regular Price</th>
<th>Sale Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Gifter Hands (Ben Carson)</td>
<td>$25.00</td>
<td>$19.95</td>
</tr>
<tr>
<td>Pelican Brief (John Grisham)</td>
<td>$29.00</td>
<td>$25.50</td>
</tr>
<tr>
<td>Built to Sell (John Warrillow)</td>
<td>$21.65</td>
<td>$17.35</td>
</tr>
<tr>
<td>Steve Jobs (Walter Issacson)</td>
<td>$35.05</td>
<td>$29.50</td>
</tr>
<tr>
<td>Nobody Moved Your Cheese (Ross Shafer)</td>
<td>$25.00</td>
<td>$21.50</td>
</tr>
</tbody>
</table>

CSS Styles

Now here comes the CSS to style our table:

html, body {
	margin: 0; padding: 0;
}
body {
	font-family: Arial;
	font-size: 0.7em;
}
table {
	float:left;
	width: 500px;
	margin: 0; padding: 0;
	border-collapse: collapse;
}
table thead tr {
	background: #568df5;
	color: #fff;
}
table tr th {
	padding: 5px;
}
table tr th:first-child {
	width: 55%;
}
table tr.odd {
	background: #ccf;
}
table tr.even {
	background: #f5f5f5;
}
table tr td:first-child {
	text-align: left;
}
table tr td {
	text-align: center;
	padding: 5px;
	font-size: 0.8em;
}

A few things to note here:

  1. Set border-collapse to collapse to eliminate the double border what appears on most tables
  2. We use thead to style the heading of this table. It’s best practice to use thead, tfoot, and tbody to further structure the table
  3. We create two classes, .odd and .even, that we’ll use with jQuery to apply a background to odd and even rows respectively.

jQuery Code Snippet

We’ll use jQuery to select and style odd and even rows. We do that by using the jQuery ‘:odd’ and ‘:even’ selectors. Remember they select odd and even elements starting at 0 (It’s zero-based) respectively.

$(document).ready(function() {
	$('tbody tr:odd').addClass('odd');
	$('tbody tr:even').addClass('even');
});

That’s pretty much it. I hope you’ve learned something from this tutorial. If you have any suggestions please do share.

{filelink=2}

2011-10-21T14:21:41-05:00
Call Now ButtonLet's Talk