This is the seventh part of some posts on using CSS in and with DT/DTTG. Though I wrote it as a single piece, I broke it up in smaller installments to keep the posts (barely) managable. Please let me know (preferably by a PM) if you find errors of any kind or are missing details. I’ll correct the first ones and try to help with the second ones.
Styling tables
Styling tables is more demanding then styling other elements. You first have to understand table structure: a table
element consists of a head and a body (thead
and tbody
). Both of them in turn are made up of row (tr
) elements. And every row consists of th
(for a table head) or td
elements which are finally defining the table cells themselves. So the whole thing looks like that:
<table>
<thead>
<tr><th>...</th><th>...</th>...</tr>
</thead>
<tbody>
<tr><td>...</td><td>...</td>...</tr>
<tr><td>...</td><td>...</td>...</tr>
...
</tbody>
</table>
You’ve just seen how to apply a very basic styling (i.e. centering) to the whole table. One detail many people want are lines dividing the columns and rows. That, however, is not something you can set for the whole table. Instead, you have to specify a border
for the td
and th
cells (i.e. those in the body and the head of the table):
table :is(td, th) {
border: 1px solid black;
padding: 0.3em;
}
Here, table :is(td.th)
is an abbreviation for table td, table th
. The border is defined as being one pixel wide, using a solid black line. This is one of the few exceptions where a pixel dimension is ok – you just want a fine line around the cells, it doesn’t really matter how big a pixel is. The padding
makes sure that the text in the cells has some space to breath.
However, these settings will result in a peculiar phenomenon in that there’s small white space now between the borders of the individual cells. They look a bit like windows in a building. To get rid of it, add border-collapse: collapse
to the style of the table
element.
Another often required feature are alternating row colors. They’re fairly easy to achieve like this:
tr:nth-child(even) {
background-color: lightblue;
}
This will display every second row with a light blue background, starting with the second row. If you want to start it with the first row, use even
instead of odd
in the above selector. If you want different colors for every second row, combine these rules like so:
tr:nth-child(even) {
background-color: lightblue;
}
tr:nth-child(odd) {
background-color: lightgreen;
}
Edit: Fixed a typo, the former version erroneously used nth-children
.
:nth-child
is a “pseudo-selector”, and there are a lot of them, so it’s worth checking them out on MDN. Instead of even
or odd
you can specify more complicated rules like 4n+1
to select the rows 1, 5, 9, 13 etc. In fact, even
is the same as 2n
and odd is 2n+1
.