How to Style a Table
Below, we apply additional style rules to define the border-style and
background-color for the table as a whole.
Table Caption
Col1 Title | Col2 Title | Col2 Title |
Row 1 Col 1 | Row 1 Col 2 | Row 1 Col 3 |
Row 2 Col 1 | Row 2 Col 2 | Row 2 Col 3 |
Row 3 Col 1 | Row 3 Col 2 | Row 3 Col 3 |
The code for this is shown below:
<style type="text/css">
#mytable
{
border-collapse: collapse;
border-style: solid;
border-width: 1px;
border-color: red;
background-color: yellow;
}
</style>
<table id="mytable">
<caption>Table Caption</caption>
<tr><th>Col1 Title</th><th>Col2 Title</th><th>Col2 Title</th></tr>
<tr><td>Row 1 Col 1</td><td>Row 1 Col 2</td><td>Row 1 Col 3</td></tr>
<tr><td>Row 2 Col 1</td><td>Row 2 Col 2</td><td>Row 2 Col 3</td></tr>
<tr><td>Row 3 Col 1</td><td>Row 3 Col 2</td><td>Row 3 Col 3</td></tr>
</table>
Note here that, rather than define the style inline as in the previous
example, I gave the table an id attribute and created an embedded style
block to define the styles for the table.
These styles are applied to the table as a whole. Below, we add a style
class to apply style to the table header cells <th> and the table data
cells <td>. The additional style rules define a border-style
and background-color and padding for the table's cells.
Table Caption
Col1 Title | Col2 Title | Col2 Title |
Row 1 Col 1 | Row 1 Col 2 | Row 1 Col 3 |
Row 2 Col 1 | Row 2 Col 2 | Row 2 Col 3 |
Row 3 Col 1 | Row 3 Col 2 | Row 3 Col 3 |
The code for this is shown below:
<style type="text/css">
#mytable1
{
border-collapse: collapse;
border-style: solid;
border-width: 2px;
border-color: red;
}
#mytable1 * th, #mytable1 * td
{
border-style: solid;
border-width: 1px;
border-color: blue;
background-color: pink;
padding: 4px;
}
#mytable1 * th
{
background-color: gray;
}
</style>
<table id="mytable1">
<caption>Table Caption</caption>
<tr><th>Col1 Title</th><th>Col2 Title</th><th>Col2 Title</th></tr>
<tr><td>Row 1 Col 1</td><td>Row 1 Col 2</td><td>Row 1 Col 3</td></tr>
<tr><td>Row 2 Col 1</td><td>Row 2 Col 2</td><td>Row 2 Col 3</td></tr>
<tr><td>Row 3 Col 1</td><td>Row 3 Col 2</td><td>Row 3 Col 3</td></tr>
</table>
In these <th> and <td> classes, I'm using descendant selectors. The
following selector:
#mytable1 * td
Means select ONLY <td> elements that are descendants of the element with
the id mytable1. Note the white space on either side of the "*". Descendant
selectors are a somewhat advanced CSS concept, but they are very useful. If you
don't use descendant selectors in this situation, the style class will be applied
to the data cells of every table on the Web page.
|