Ajax JavaScript CSS HTML 5 Gecko XUL Forum

Pretty HTML Table with CSS

Without Ajax framework, but with just a JavaScript function to alternate colors, this gives HTML tables the look of that of magazine or professional website.

The demonstration is done both on a complete structure and simplified structure (see article in Table in HTML 4 and 5 for more detail). The record is exactly the same.

Simple HTML code for a table

The caption tag is an option.

<table>
<caption></caption>
<tr>
  <th></th>
...three cells...
</tr>
<tr>
<th></th><td></td><td></td><td></td>
...four row of three cells each...
</tr>
</table>

Note the use of <th> header tag in top row and first column.

The CSS code

It applies broadly to all tables in the page.

table
{
border-collapse:collapse;
width:100%;
max-width:700px;
min-width:400px;
text-align:center;
} caption
{
caption-side:bottom;
font-weight:bold;
font-style:italic;
margin:4px;
} table,th, td
{
border: 1px solid gray;
} th, td
{
height: 24px;
padding:4px;
vertical-align:middle;
} th
{
background-image:url(table-shaded.png);
} .rowtitle
{
background: #9CF;
font-weight:bold;
}

The attributes border-collapse and border allow to make a border of uniform width.

The caption-side attribute puts the label below the table. You can omit the attribute to keep it on top.

The descriptor .rowtitle is used for row headers in the second table, for the demonstration. One may also use <th> tags as in the first one. But in this case the hight must be the same for headers and other cells.

text-align and vertical-align center labels. We can align them differently, with stylesheets.

Other attributes are for presentation options, including maximum size and minimum size, the row heights.

The JavaScript function

The alternation of colors for the row of the tables is obtained by a JavaScript function. It allow to easily edit the rows of the table without having to worry about the colors.

It applies broadly to all rows in all tables in the page.

function colourize()
{
var dnl = document.getElementsByTagName("tr"); for(i = 0; i < dnl.length; i++)
{
if((Math.round(i / 2) * 2) == ((i / 2) * 2) )
dnl.item(i).style.background="#E8E8FF"; }
} window.onload = colourize;

A DOMNodeList object containing all <tr> tag is created, and the color attribute is changed for all the tags whose index is odd.

Pretty HTML table demonstration

Simple code

It is a table tag with <tr> rows and <td> or <th> cells.

It uses <th> tags for the headers of columns and rows.

Usage Fast Safe
Desktop C++ Pascal
Server side PHP Java
Client side JavaScript CSS
System C Go

Full code

It adds the caption, thead, and tbody tags. The rendering is the same in both Firefox and Internet Explorer.
The choice of background images and colors is independent of the structure of the table.

Caption : Label of the table
Usage Fast Safe
Desktop C++ Pascal
Server side PHP Java
Client side JavaScript CSS
System C Go