css 101

Tables

On the internet of the 1990s, web developers used HTML tables to lay out pages. This was very convenient, but led to exactly the mess we described at the beginning of this tutorial - tons of display-oriented code intermingled with the true markup of the page. This made redesigning web sites very difficult, as well as difficult to use by assistive technologies such as screen readers for the blind.

When CSS came along, developers had to learn an entirely new way of laying out pages, using CSS rather than tables. People started thinking of HTML tables as "the wrong way to do things." Well, yes and no. It's true that you really, really shouldn't be doing page layout with tables unless you want to create an unmaintainable rat's nest of code. But you should continue to use tables for displaying tabular data, such as charts, schedules, budgets, or anything else that is naturally tabular. This section is about styling legitimate tables, not page layout (we'll cover that in our CSS 201 tutorial).

In the example below, we've created a simple table of staff contacts. We're showing both the HTML and the corresponding CSS so you can see how they relate to one another. For the most part, all of the CSS rules are things you've already encountered in this tutorial. The most significant new item is the border-collapse:collapse property. This is used to make sure that any overlapping borders truly overlap one another, rather than appearing side-by-side. Also note the use of the "dotted" bottom border property on normal cells, which makes those rows a bit more elegant.

Perhaps the biggest difference is that with HTML tables, you're forced to either show or hide all of your borders - you either get a grid or you don't. With a CSS-based table, we're able to enable an outside border for the whole table and for the header row, but only a bottom border for the table cells. This gives the appearance of having rows but no columns, which is nice. Notice again the use of nested selectors, so we can attach styles to cells and rows of just this table, not all tables that might appear on the page.

Staff Contacts
Jane Goodall Director 555-6715
Rob Jackson Chief Architect 555-7413
Elvin Bishop Employee 555-5168

Here is the HTML and the CSS for the table:

As an exercise, try to imagine how you might color the phone number column of this table.

That's a simple example, but there's a LOT you can do with CSS-based tables. For more ideas, or to find sample CSS to work with, try Smashing Magazine's CSS table gallery.

More on CSS tables from W3Schools