Wednesday, February 27, 2013

How to style table borders with CSS

Let's imagine you have a HTML table containing some data, and want to style this table using CSS stylesheet.

Interesting Data
header 1 header 2
footer 1 footer 2
cell 1 cell 2
cell 3 cell 4
cell 5 cell 6

<html>
<head>
<!-- CSS rules embedded in HTML  -->
<style>
.table_for_data {
   width: 300px;
   border-collapse: collapse;
}
.table_for_data colgroup col.left {
   border-right: 1px solid black;
   width:50%; 
}
.table_for_data thead tr, .table_for_data tbody tr {
   border-bottom: 1px solid black;
}
.table_for_data td {
   padding-left: 5px;  
}
</style>
</head>

<body>
<!-- HTML code of the table. -->
<table class="table_for_data">
 <caption> Interesting Data </caption>
  <col class="left"> <!-- no ending tag -->
  <col class="right">
 <thead>
  <tr> 
   <th>header 1</th>
   <th>header 2</th>
  </tr>
 </thead>
 <tfoot>
  <tr> 
   <td>footer 1</td>
   <td>footer 2</td>
  </tr>
 </tfoot>
 <tbody>
  <tr> 
   <td>cell 1</td>
   <td>cell 2</td>
  </tr>
  <tr> 
   <td>cell 3</td>
   <td>cell 4</td>
  </tr>
  <tr> 
   <td>cell 5</td>
   <td>cell 6</td>
  </tr>
 </tbody>
</table>
</body>
</html>
Within your CSS you can:
  • add a border to table's rows using a CSS selector for tr elements
  • add a width to table's columns using a CSS selector for col tags
Check out on the W3C.org web site what styles you can add to table columns: http://www.w3.org/TR/CSS2/tables.html#columns

No comments :

Post a Comment