Tables and CSS
For more sophisticated control over borders, spacing, and padding, you can and should use CSS rather than the border
, cellspacing
, and cellpadding
attributes. The CSS properties are as follows:
-
The
padding
CSS property corresponds to thecellpadding
table attribute. -
The
border-spacing
CSS property corresponds to thecellspacing
table attribute. -
The
border
CSS property corresponds to theborder
table attribute.
The CSS properties allow us to use any valid CSS length: px
are okay, as are em
, pt
, and so on. We’ll stick with pixels for our example below.
Example 4.9. Table: CSS Borders
<html> <head> <style> table { background: #009900; border: 4px #ff00ff ridge; border-spacing: 5px; } td { background: #ffff00; padding: 10px; border: 2px #0000ff dotted; } td.middle { border: 2px #ff0000 solid; padding-right: 25px; } </style> </head> <body> <table border="0" cellpadding="0" cellspacing="0" summary="Table with CSS borders"> <tr> <td>Left Cell</td> <td class="middle">Middle Cell</td> <td>Right Cell</td> </tr> </table> </body> </html>
The overall table has a green background and a ridged, lavender border. The result is garish to say the least… presumably your tables will be far more subdued and tasteful.
Ordinary table cells have a yellow background, ten pixels of padding, five pixels of border-spacing (i.e. cellspacing), and a blue, dotted border.
Table cells with class="middle"
have an extra fifteen pixels of padding to the right and a red, solid border.
Note that some modern browsers still don’t support the border-spacing
attribute. If you’re using one of these browsers, all three cells will be adjacent to each other, and you will not see the green background of the table itself. One workaround is to use CSS to do your primary styling, and the border
table attribute for backup.