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]