How do I get padding between table cells, but not around the entire table?
Asked Answered
M

2

6

I want to have a table with padding between each of the cells, but not around the outer edge cells, that is, not around the table itself.

Using:

border-collapse : separate;
border-spacing  : 0.5em;

gives me padding everywhere, while using:

border-collapse : collapse;

gives no padding anywhere.

Attempting an alternate approach, I can get padding solely between the cells horizontally using a td + td selector. However I can't use a tr + tr selector because it seems tr ignores margin, padding and border rules.

And, of course, padding on a plain td selector applies to all cells, even the outer-edges of the outer cells.

This only has to work for current-generation browser - no IE 6 or 7 for me thank you very much. And I am not going to loose any sleep over IE 8, though it would be nice if that worked.

Marvellamarvellous answered 15/6, 2011 at 4:58 Comment(1)
But IE7 or IE8? (i.e. no :last-child answers?)Cornett
C
4

This isn't a perfect solution, as it uses padding instead of border spacing. Possibly it will work for your problem though.

HTML:

<table>
    <tr>
        <td>Data 1</td>
        <td>Data 2</td>
    </tr>
    <tr>
        <td>Data 3</td>
        <td>Data 4</td>
    </tr>
</table>

And the CSS:

table {
    border: 1px red solid;
    border-collapse: separate;
}

td {
    background-color: green;
    border: 1px black solid;
    padding: 10px;
}

td:first-child {
    padding-left: 0px;
}

td:last-child {
    padding-right: 0px;
}

tr:first-child td {
    padding-top: 0px;
}

tr:last-child td {
    padding-bottom: 0px;
}

Produces:

enter image description here

Also on jsFiddle.

Cornett answered 15/6, 2011 at 5:17 Comment(3)
Actually, that looks precisely like what I am looking for - I was not aware that there is a last-child pseudo-class.Marvellamarvellous
Yes, but I warned you: It only works > IE8. :(Cornett
Nice, but this not working with colspan and rowspan in a complex table. ;)Clintclintock
E
-1

Can you fiddle with the markup to add .first to the first cell in a row and .last to the last, and I guess also to the first and last rows, and then pad appropriately?

Extrasystole answered 15/6, 2011 at 5:16 Comment(1)
Not realistically - it would be a significant effort and a maintenance nightmare.Marvellamarvellous

© 2022 - 2024 — McMap. All rights reserved.