Home » Articles

Articles

Table spacing and borders cross browser using plain HTML and CSS

Table spacing behaves differently depending upon the browser. Most of the time, default cellspacing and cellpadding are "2" if they are not set by the HTML or CSS code. In order to control the spacing, you can either specify it in the HTML portion of the table or you can specify it in the table and td portion of the CSS.

Default cellspacing and padding

HTML Table Example:
<table border="1">
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</table>

PC
IE 5.5
FireFox 1.02
Opera 7.54


HTML Table Example:
<table cellspacing="1" cellpadding="1" border="1">
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</table>

PC
IE 5.5
FireFox 1.02
Opera 7.54


CSS Example:
<style type="text/css">
table, td
{
margin: 0;
padding: 0;
}
</style>

<table border="1">
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</table>

PC
IE 5.5
FireFox 1.02
Opera 7.54

Notice that without cellspacing or cellpadding in the HTML, the default spacing visually reverts back to "2" with the CSS trying to control the margin and padding. Something else is needed.


Now add border-collapse: collapse to the above CSS so that the cellspacing = 0.

CSS Example:
<style type="text/css">
table, td
{
margin: 0;
padding: 0;
border-collapse: collapse;
}
</style>

<table border="1">
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</table>

PC
IE 5.5
FireFox 1.02
Opera 7.54


So how do we get these browsers to look the same? Remove the border from the HTML and add it to the CSS.

CSS Example:
<style type="text/css">
table, td
{
margin: 0;
padding: 0;
border-collapse: collapse;
border: 1px solid #000;
}
</style>

<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</table>

PC
IE 5.5
FireFox 1.02
Opera 7.54

Articles