Set Cellpadding and Cellspacing in CSS

It is fairly simple to set the cellpadding and cellsetting of a table in HTML but there are some drawbacks with the HTML option as explained below. The other option is to set the cellpadding and cellsetting by defining the properties in the CSS. The cellspacing and cellpadding properties in CSS are largely the same as the HTML version. The HTML code would look like this:

Cellpadding CSS

The CSS alternative for cellpadding would be: This applies a 10 pixel padding to the cell.

Cellspacing CSS

For cellspacing the CSS code would be: This applies spacing of 10 pixels to cells in the table. Remember that the default value for cellpadding is 0 (padding: 0px) and the same applies to cellspacing (border-collapse: collapse). By setting the cellspacing the border-collapse property is now set to separate rather than collapse.

Why is CSS better?

The main reason for going the CSS route rather than using HTML is that with CSS the table properties can be set globally across multiple webpages. The HTML option means setting these properties for each and every table on the website. Another advantage is that with CSS the horizontal and vertical borders can be set with cellspacing. This cannot be done with HTML. Remember that this separate horizontal and vertical cellspacing will also apply between the outer cells and table border which can be undone by setting negative margins in the CSS. Let’s look at a few examples.

Example 1

We want to set the cellpadding to 8 pixels and the cellspacing to be zero.

Example 2

We want to set the cellspacing to 4 pixels and the cellpadding to zero.

Example 3

We want to set the cellspacing to 4 pixels and the cellpadding to 2 pixels.

Example 4

We want to set different horizontal and vertical cellspacing between the cells in the table. The horizontal cellspacing is 4 pixels, the vertical cellspacing is 6 pixels and the cellpadding is 8 pixels.

Potential Problems

The above CSS should work in most popular browsers but there may be some issues with Internet Explorer and particularly below version 7. In these browsers there are also issues with setting the properties in HTML, such as cellspacing: 0 so border-collapse: collapse has to be used for no cellspacing. If you want to override the CSS settings for individual tables, you may find some difficult when it comes to cellspacing in particular. One of the ways around this is to border-collapse: collapse code after defining the cellspacing in CSS. To ensure that the cellspacing is not overridden, include border-collapse: separate before defining the cellspacing properties.

Leave a Comment