HTML Post #5: Tables & Whitespace

Tables  are one of the fundamentals of html. At one point in time, everyone’s site was built inside a table. It was really easy to do this. Also, whitespace, including spaces, tabs, and new lines, don’t matter much in html, but there are ways to get the whitespace you desire.

Tables

Here’s a 2×2 basic table:

<table border="1">
 <tr>
  <td>Row 1, Cell 1</td>
  <td>Row 1, Cell 2</td>
 </tr>
 <tr>
  <td>Row 2, Cell 1</td>
  <td>Row 2, Cell 2</td>
 </tr>
</table>

Which looks like this:

Row 1, Cell 1Row 1, Cell 2
Row 2, Cell 1Row 2, Cell 2

Note that I put border=”1″. If I put border=”0″, no border would be added, like this:

Row 1, Cell 1Row 1, Cell 2
Row 2, Cell 1Row 2, Cell 2

Spanning

Each cell in the table can span across, down, or both directions. This is very similar to the merge cell function in Excel. There are a few points to keep in mind. When you span several columns, the next cell in the html code will be the next cell on the screen. Likewise, when you span several rows, you have to skip that cell on the following row(s). Here’s an example:

<table border="1">
 <tr>
  <td rowspan="2">I span 2 rows.</td>
  <td colspan="2">I span 2 columns across.</td>
 </tr>
 <tr>
  <td>I am a single cell.</td>
  <td>I am a single cell.</td>
 </tr>
</table>
I span 2 rows.I span 2 columns across.
I am a single cell.I am a single cell.

Whitespace

Did you notice that the table in the last example could use some text alignment? Maybe vertically align the rowspan cell to the top? Maybe center the colspan cell? How about making the rowspan cell into two lines? Let’s take a look.

Here’s how to vertically align to the top:

<table border="1">
 <tr>
  <td rowspan="2" style="vertical-align: top">I span 2 rows.</td>
  <td colspan="2">I span 2 columns across.</td>
 </tr>
 <tr>
  <td>I am a single cell.</td>
  <td>I am a single cell.</td>
 </tr>
</table>
I span 2 rows.I span 2 columns across.
I am a single cell.I am a single cell.

You could also set vertical-align: bottom for the bottom or middle for the middle.

Centering the colspan cell:

<table border="1">
 <tr>
  <td rowspan="2">I span 2 rows.</td>
  <td colspan="2" style="text-align: center">I span 2 columns across.</td>
 </tr>
 <tr>
  <td>I am a single cell.</td>
  <td>I am a single cell.</td>
 </tr>
</table>
I span 2 rows.I span 2 columns across.
I am a single cell.I am a single cell.

Other possibilities are “left”, “right”, and “justify”.

And finally, inserting a line break:

<table border="1">
 <tr>
  <td rowspan="2">I span<br />2 rows.</td>
  <td colspan="2">I span 2 columns across.</td>
 </tr>
 <tr>
  <td>I am a single cell.</td>
  <td>I am a single cell.</td>
 </tr>
</table>
I span
2 rows.
I span 2 columns across.
I am a single cell.I am a single cell.