Oleksandr IY
Oleksandr IY

Reputation: 3146

CSS - Border only inside the table with the cell spacing

I am trying to figure out how to add border only inside the table with the cell spacing. When I do:

table {
  border-collapse: collapse;
  border-spacing: 4px;
}
table td, table th {
  border: 1px solid black;
}

It works almost fine just cells without spacing. How to achieve that?

Thanks

Upvotes: 0

Views: 6603

Answers (2)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201866

The CSS code posted is correct and causes borders around cells (but around the table as a whole) and 4px spacing between cells, on conforming browsers. I suppose you were testing this on IE 7 or older, which do not support the border-spacing property.

I’m afraid there is no simpler workaround than to create a table without any borders and put an inner element inside each cell, making that cell occupy the entire cell except small margins, and draw borders around the inner elements. This probably gets ugly, so I’d rather let the presentation on IE 7 be suboptimal.

(For some reason, border-spacing does not seem to work in jsfiddle. Probably some general rule overrides a normal attempt to set the property.)

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382454

If you're trying to write CSS rules for tables on which you've defined the cellspacing attribute, a solution could be this :

table[cellspacing] {
  border-collapse: collapse;
  border-spacing: 4px;
}
table[cellspacing] td, table[cellspacing] th {
  border: 1px solid black;
}

But it would be much cleaner and more efficient to give a class to your table (<table class="withspace">). So you would more classically do

table.withspace {
  border-collapse: collapse;
  border-spacing: 4px;
}
table.withspace td, table.withspace th {
  border: 1px solid black;
}

EDIT : just in case, if what you want is simply to have some space in your cells, add a padding value in your css :

table {
  border-collapse: collapse;
  border-spacing: 4px;
}
table td, table th {
  border: 1px solid black;
  padding: 4px;
}

Upvotes: 1

Related Questions