乐闻世界logo
搜索文章和话题

How to set cellpadding and cellspacing in css

3个答案

1
2
3

In CSS, there is no direct equivalent to the HTML attributes cellpadding and cellspacing. However, you can achieve similar effects using certain CSS properties.

Implementing cellpadding in CSS

In HTML, the cellpadding attribute sets the space between the content of a table cell and its borders. In CSS, you can achieve the same effect by setting the padding property on the cells.

For example, to set a 10px padding for all cells, you can write:

css
td, th { padding: 10px; }

Implementing cellspacing in CSS

The cellspacing attribute in HTML represents the distance between cells. In CSS, this can be achieved using the border-spacing property, but it only applies when border-collapse is set to separate.

Here's an example setting the spacing between cells to 5px:

css
border-collapse: separate; border-spacing: 5px; }

If you use border-collapse: collapse;, the borders are merged, and border-spacing will not function. In border-collapse: collapse; mode, there is no space between cells as the borders are merged together. If you want a gap effect with merged borders, you can achieve it by adding transparent borders, for example:

css
td, th { border: 5px solid transparent; }

Combining Both

To combine padding and border-spacing to simulate the traditional cellpadding and cellspacing effects, you can do the following:

css
border-collapse: separate; border-spacing: 5px; } td, th { padding: 10px; }

In this example, there is a 5px spacing between table cells (similar to cellspacing), and a 10px padding between the content and the borders of each cell (similar to cellpadding).

2024年6月29日 12:07 回复

This technique is compatible with Internet Explorer 6 and later versions, Google Chrome, Firefox, and Opera:

css
table { border-collapse: separate; border-spacing: 10px; /* cellspacing */ *border-collapse: expression('separate', cellSpacing = '10px'); } table td, table th { padding: 10px; /* cellpadding */ }

The * declaration targets Internet Explorer 6 and 7; other browsers will ignore it without issue.

The expression('separate', cellSpacing = '10px') returns 'separate', but both statements execute as in JavaScript—passing additional parameters beyond expectations, and all are evaluated.

2024年6月29日 12:07 回复

As far as I know, setting margins on table cells has no effect. The true CSS equivalent of cellspacing is border-spacing, but it doesn't work in Internet Explorer.

shell
border-collapse: collapse

As mentioned earlier, you can reliably set cell spacing to 0 using this property, but for any other value, I believe the only cross-browser method is to continue using the cellspacing attribute.

2024年6月29日 12:07 回复

你的答案