Styling Columns

Being able to apply styles to individual elements of our table is easy, we just apply the style to the appropriate th or td tag. Similarly we can apply styles to entire rows of our table by adding them to the appropriate tr tag. What is not so obvious is how we can apply styles to entire columns within the table. This is where the last of the tags that we showed in the first table tutorial comes in - the colgroup tag.

The colgroup tag (or tags) must always come after the caption (if present) and before the thead. There are two ways that we can use the colgroup to apply styles to the columns in our table depending on whether we want to apply the styles to individual columns or to groups of columns. We can even combine the two methods if we like.

Let's look at an example of how we can set things up so that we can style the columns of a three column tableindividually:

<colgroup>
<col />
<col />
<col />
</colgroup>

With the above code added into the appropriate spot in our table we now have a separate col tag that references each column within our table. The first col tah corresponds to the first column and so on. We can easily add a class or id attribute to the appropriate col tag in order to apply selected styles to that column of the table provided that those styles are not overridden by row or cell styles (which are defined closer to the individual cells of the table).

The alternative method uses multiple colgroup tags without the col tags in them. Instead we add a span attribute to each colgroup to indicate how many columns that particular colgroup represents and we can add the id and class attributes directly to the colgroup to style those columns. So if we have a six column table and we want the first two columns styled one way and the other four styled a seconnd way we could use:

<colgroup span="2">
</colgroup>
<colgroup span="4">
</colgroup>

The final alternative is to combine these two methods so if we actually needed the first and second columns of a six column table to each be styled separately with the other four sharing the same style we would use:

<colgroup>
<col />
<col />
</colgroup> <colgroup span="4">
</colgroup>

We can now apply styles to the individual col tags for the first two coluns and to the colgroup for the last four as a group.

Note that some of the older browsers that may still be used by some of your visitors do not properly understand the colgroup tag and so will not apply column styling defined this way. If you absolutely must have the styles applied to the columns then the only method that those browsers understand is to apply a class attribute to the individual cells in the column.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate