Styling a TABLE Border

How do I apply a border to a table and still make it validate? This is a common question many webmasters ask when they begin to design web pages in XHTML - I know I did! :) Previously all we had to do was use the attribute bordercolor=#000 in the table tag and that was it - but with XHTML and because this is still only a Microsoft proprietary attribute, this won't work... actually it might but it won't validate as valid XHTML!

Creating a table in XHTML with CSS

The solution is to use Cascading StyleSheets or (better known as) CSS and the sample code below will help you get an idea how this can be achieved without too much effort.

Our sample XHTML/CSS web page with 3 different tables

First, we have to set up the CSS which goes between the <head> and </head> tags:

code:
<head>
<style type="text/css">
<!--

table {
  background-color:#FFF;
  width:100%;
  border-collapse:collapse;
}

/* the border will be defined by the td tags */
td.BorderMeRed {
  background-color:#FFF;
  border:2px solid red;
  padding:10px;
}

/* let's do a blue... */
td.BlueWho {
  background-color:#FFF;
  border:2px solid blue;
  padding:15px;
}

/* and of course a default one */
td {
  background-color:#FFF;
  border:1px solid black;
  padding:5px;
}

-->
</style>
</head>

Please note the padding property in the CSS above, it's there to simulate the missing cellpadding=n attribute in the table tag which is defined usually in 'regular' HTML.

Sample XHTML code and Output

XHTML / CSS table with RED border - BorderMeRed

code:
<body>
<h2>XHTML table with red border</h2>
<table>
  <tr> 
    <td class="BorderMeRed">Cell 1</td>
    <td class="BorderMeRed">Cell 2</td>
  </tr>
  <tr> 
    <td class="BorderMeRed">Cell 3</td>
    <td class="BorderMeRed">Cell 4</td>
  </tr>
</table>

The table looks like this:

XHTML table with red border

Cell 1 Cell 2
Cell 3 Cell 4

* * * * * * * * * *

XHTML / CSS table with BLUE border - BlueWho

code:
<h2>XHTML table with blue border</h2>
<table>
  <tr> 
    <td class="BlueWho">Cell 1</td>
    <td class="BlueWho">Cell 2</td>
  </tr>
  <tr> 
    <td class="BlueWho">Cell 3</td>
    <td class="BlueWho">Cell 4</td>
  </tr>
</table>

The table looks like this:

XHTML table with blue border

Cell 1 Cell 2
Cell 3 Cell 4

* * * * * * * * * *

The default XHTML / CSS table

code:
<h2>The final, default XHTML table</h2>
<table>
  <tr> 
    <td>Cell 1</td>
    <td>Cell 2</td>
  </tr>
  <tr> 
    <td>Cell 3</td>
    <td>Cell 4</td>
  </tr>
</table>
</body>

The table looks like this:

The final, default XHTML table

Cell 1 Cell 2
Cell 3 Cell 4

* * * * * * * * * *

TOP

How old are you?

 Teenager

 20 something

 30 something

 40 something

 Over 50