Jonathan Wood
Jonathan Wood

Reputation: 67175

Controlling Spacing Between Table Cells

I'm trying to create a table where each cell has a background color with white space between them. But I seem to be having trouble doing this.

I tried setting td margins but it seems to have no effect.

table.myclass td {
    background-color: lime;
    margin: 12px 12px 12px 12px;
}

If I do the same thing with padding, it works, but then I don't have the spacing between cells.

Could someone help me with this?

table.test td {
  background-color: lime;
  margin: 12px 12px 12px 12px;
  /*padding: 12px 12px 12px 12px;*/
}
<table class="test">
  <tr>
    <td>Cell</td>
    <td>Cell</td>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
    <td>Cell</td>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
    <td>Cell</td>
    <td>Cell</td>
  </tr>
</table>

Upvotes: 92

Views: 221330

Answers (5)

Buggabill
Buggabill

Reputation: 13901

Check this fiddle. You are going to need to take a look at using border-collapse and border-spacing. There are some quirks for IE (as usual). This is based on an answer to this question.

table.test td {
  background-color: lime;
  margin: 12px 12px 12px 12px;
  padding: 12px 12px 12px 12px;
}

table.test {
  border-collapse: separate;
  border-spacing: 10px;
  *border-collapse: expression('separate', cellSpacing='10px');
}
<table class="test">
  <tr>
    <td>Cell</td>
    <td>Cell</td>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
    <td>Cell</td>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
    <td>Cell</td>
    <td>Cell</td>
  </tr>
</table>

Upvotes: 36

Quentin
Quentin

Reputation: 943108

Use the border-spacing property on the table element to set the spacing between cells.

Make sure border-collapse is set to separate (or there will be a single border between each cell instead of a separate border around each one that can have spacing between them).

Upvotes: 120

table.test td {
    background-color: lime;
    padding: 12px;
    border:2px solid #fff;border-collapse:separate;
}

Upvotes: 3

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201528

To get the job done, use

<table cellspacing=12>

If you’d rather “be right” than get things done, you can instead use the CSS property border-spacing, which is supported by some browsers.

Upvotes: 3

Halcyon
Halcyon

Reputation: 14971

Use border-collapse and border-spacing to get spaces between the table cells. I would not recommend using floating cells as suggested by QQping.

JSFiddle

Upvotes: 2

Related Questions