How can I control cellpadding and cellspacing in a CSS stylesheet to obtain the same effect as when putting the attributes on the table tag?
Simply apply
padding:
and
margin:
css properties to individual components of the table, th, tr, td etc. as you see fit...
Let's say you want 5 cellpadding and 10 cellspacing, do this:
HTML
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>Cell</td>
</tr>
</table>
CSS
td
{
margin:10px;
padding:5px
}
Also, if you want cellspacing="0"
, don't forget to add border-collapse: collapse
in your table
's stylesheet.
Setting margins on table cells doesn't really have any effect as far as I know. The true CSS equivalent for cellspacing
is border-spacing
- but it doesn't work in IE. You can use border-collapse: collapse
to reliably set cell spacing to 0 as mentioned, but for any other value I think the only cross browser way is to keep using the cellspacing
attribute.
table {
border-collapse: collapse; // 'cellspacing' equivalent
}
table td,
table th {
padding: 0; // 'cellpadding' equivalent
}
TBH. For all the fannying around with CSS you might as well just use cellpadding="0" cellspacing="0" since they are not deprecated...
Anyone else suggesting margins on 's is a DONKEY and obviously has not tried this.
None of the answers here are complete, so I'll merge into a comprehensive one.
First of all, you can control cellspacing by applying the border-spacing
CSS property to your table. This will work in almost all popular browsers except for IE up through v7. For browsers which support it, this property will even allow separate horizontal and vertical spacing. If you need to support IE 5, 6, or 7, you're almost out of luck.
However, I say "almost" because these browsers still support the border-collapse
property, which merges the borders of adjoining table cells. If you're trying to eliminate cellspacing (i.e. cellspacing="0"
) then border-collapse:collapse
should have the same effect: no space between table cells. This support is buggy, though, as it does not override an existing cellspacing
HTML attribute on the table element.
In short: for non-IE 5-7 browsers, border-spacing
handles you. For IE, if your situation is just right (you want 0 cellspacing and your table doesn't have it defined already), you can use border-collapse:collapse
.
Note: For a great overview of CSS properties that one can apply to tables and for which browsers, see this fantastic Quirksmode page.