Wednesday, June 13, 2007
HTML Tables and Styles

Have you ever tried to add borders to individual cells in an HTML table using style sheets? Something similar to <table border="1"> only done with CSS.

I had a requirement to put a 1 pixel black border between all cells in an HTML table. I wanted to do this without having to put a style or class attribute into every cell in the table. I thought: "How hard can this be?". There has to be a way of doing this with a single style attribute.

But after a quick search on the web with too many non-relevant results, (I mean what can you search for that doesn't bring back over a million hits). I decided to come up with my own technique:

<style type="text/css">

  table.border tr td,
  table.border tr th
{border:1px solid black;}

  table.border {border-collapse:collapse;}

</style>

 

<table class="border">

  <tr>

    <th>Header 1</th> 

    <th>Header 2</th> 

    <th>Header 3</th> 

    <th>Header 4</th> 

  </tr>

  <tr>

    <td>Data 1</td> 

    <td>Data 2</td> 

    <td>Data 3</td> 

    <td>Data 4</td> 

  </tr>

  <tr>

    <td>Data 1</td> 

    <td>Data 2</td> 

    <td>Data 3</td> 

    <td>Data 4</td> 

  </tr>

</table>

Yields the following output:

Header 1 Header 2 Header 3 Header 4
Data 1 Data 2 Data 3 Data 4
Data 1 Data 2 Data 3 Data 4

Is there a better way of doing this?

Bo Durban


Wednesday, June 13, 2007 2:13:21 PM (Eastern Daylight Time, UTC-04:00)  #     Comments [2]  

Wednesday, June 13, 2007 3:35:15 PM (Eastern Daylight Time, UTC-04:00)
You nailed it.

The only change I would make to the above HTML is to give the table an ID as well. This will allow you to tap into it using the DOM (using the ID is the easiest of all methods), as well as supply additional formatting in CSS.
Thursday, June 21, 2007 2:02:08 PM (Eastern Daylight Time, UTC-04:00)
Hi Bo.

The code will be better.

Other form to put the tables will be:

<table class="class_Name">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
<tr>
<td>Data 3</td>
<td>Data 4</td>
</tr>
</tbody>
<tfoot>
<tr><th colspan=2>Footer</th></tr>
</tfoot>
</table>

Is more semantic and more easy to read.

"Saludos"
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: )  

Enter the code shown (prevents robots):