Web Design & Development

[ Web Design & Development Topics ]

Creating Tables in (X)HTML

Creating a table

cell1 cell2
cell3 cell4

Here is what the source code looks like:

<table border="1" cellspacing="4" cellpadding="4">
<tr>
<td>cell1</td>
<td>cell2</td>
</tr>
<tr>
<td>cell3</td>
<td>cell4</td>
</tr>
</table>

Notice the cellspacing and cellpadding above, this is what makes the space between and within the cells. Also notice the border size. If you set this to zero the table border will not be visible on the Web. Lets make the same table but have a border of zero and larger cellspacing and cellpadding:

cell1 cell2
cell3 cell4

Now the code looks like this:

<table border="0" cellspacing="8" cellpadding="8">
<tr>
<td>cell1</td>
<td>cell2</td>
</tr>
<tr>
<td>cell3</td>
<td>cell4</td>
</tr>
</table>

Note: If you don't put in a value for the border it defaults to 1. If you don't put in a value for the cellpadding or cellspacing they default to 0 (no spacing).

Now lets try using colspan and cellspan to merge cells:

cell1cell2 cell3
cell4 cell5 cell6
cell7 cell9

<table border="1" cellspacing="4" cellpadding="4">
<tr>
<td colspan="2">cell1cell2</td>
<td>cell3</td>
</tr>
<tr>
<td>cell4</td>
<td rowspan="2">cell5cell8</td>
<td>cell6</td>
</tr>
<tr>
<td height="30">cell7</td>
<td>cell9</td>
</tr>
</table>

Tables in tables are useful sometimes for formatting as well.

Cell1 Cell2
Cell3
CellA CellB
CellC CellD

 

Establishing the width of the table

You can use pixel sixe to set the sizes:

cell1 cell2
cell3 cell4

The code looks like this:

<table width="400" border="1" cellspacing="4" cellpadding="4">
<tr>
<td width="100">cell1</td>
<td>cell2</td>
</tr>
<tr>
<td>cell3</td>
<td>cell4</td>
</tr>
</table>

You can also use percentages to set the sizes:

cell1 cell2
cell3 cell4

The code looks like this:

<table width="90%" border="1" cellspacing="4" cellpadding="4">
<tr>
<td width="40%">cell1</td>
<td>cell2</td>
</tr>
<tr>
<td>cell3</td>
<td>cell4</td>
</tr>
</table>

When to use fixed width versus percentage

There are mixed feelings about whether fixed width or percentage based is better web design. Percentage based ensures optimum use of the screen "real estate" but it also causes things to look stretched out in cases. Fixed width on the other hand ensures everything is just like you designed it. But if you designed it for a 800 x 600 screen it will look small on a 1024 x 728 monitor.

An empty cell

If you do not have anything in the cell it will not appear on the page (there will not be a border in that cell) like this:

cell2
cell3 cell4

For it to show up you need to put &nbsp; in the cell (a blank space)

Learn more at: