Use CSS to control HTML table cellpadding and cellspacing


If you have ever used HTML's <table> tag, you probably know that you could use cellpadding= to control the padding around the cells, and cellspacing= to control the spacing between the cells.  Then HTML5 and CSS3 comes along and you have to use CSS to do most of the configurations and styles, and you are wondering how to use CSS to do the same thing.  Imaging the following code that produces a basic HTML table.

<table id="mytable">
    <thead>
        <tr>
            <td>Column 1</td>
            <td>Column 2</td>
            <td>Column 3</td>
        </tr>
    </thead>
    <tbody>
    <tr>
        <td>Cell 1</td>
        <td>Cell 2</td>
        <td>Cell 3</td>
    </tr>
    <tr>
        <td>Cell 4</td>
        <td>Cell 5</td>
        <td>Cell 6</td>
    </tr>
    <tr>
        <td>Cell 7</td>
        <td>Cell 8</td>
        <td>Cell 9</td>
    </tr>
    </tbody>
</table>

The above code produces the following HTML table, which doesn't look like much yet.

HTML Table (Before)

By adding a little CSS, as shown below

#mytable {
    background-color: #080;
    border-spacing: 1px;
    border-collapse: separate;
}

#mytable thead {
    background-color: #9f9;
}

#mytable tbody {
    background-color: #fff;
}

#mytable td {
    padding: 5px;
    font-family: verdana;
    font-size: 11px;
}
Your HTML table now becomes

csstable_after

So how did that happen?  Let's take a look at the CSS code:

#mytable {
    background-color: #080;
    border-spacing: 1px;
    border-collapse: separate;
}

This piece of code targets the Table with ID of #mytable, and give it a background color of #080.  This will become the Table's border color.  border-spacing of 1px replaces the old cellpadding=1.  If you want to have a bigger spacing between the table cells, you just need to make this number larger.
 
#mytable thead {
    background-color: #9f9;
}

This gives the header line (first row) a background of #9f9, which gives a slightly lighter green background.
 
#mytable tbody {
    background-color: #fff;
}

This makes the background of the rest of the cells white (#fff).
 
#mytable td {
    padding: 5px;
    font-family: verdana;
    font-size: 11px;
}

This defines the styles of the <td> tag.  The padding: 5px replaces the old cellpadding=5.  The other two lines defines the font and size of the text used in the table.