Home  »  ArticlesGuidesProgrammingTechnologyTips   »   How to Properly Set Cellspacing and Cellpadding for HTML Tables in CSS

How to Properly Set Cellspacing and Cellpadding for HTML Tables in CSS

Here will show you the correct way to set cellspacing and cellpadding in HTML tables using just CSS rules.

It is more common than you might imagine finding web designers setting cellspacing and cellpadding to HTML tables using attributes as shown below:

<table cellspacing="10" cellpadding="10"></table>

It is not the best practice to use the above method as it is not easy to maintain for the designer or the team, also these attributes have been deprecated for a while now.

The good news is that with CSS there is a much more elegant and friendly way to set cellspacing and cellpadding in your HTML tables.

To control Cellspacing with CSS, you can apply the border-spacing CSS property to your table. Here we add the optional border-collapse CSS property to specify that the cells should have separate borders.

table { 
    border-spacing: 10px;
    border-collapse: separate;
}

As for Cellpadding, you can simply use padding on the table cells as shown below.

td { 
    padding: 10px;
}

One of the advantages when using CSS to set the cellspacing and cellpadding is that in both cases you can control the spacing of the top, right, bottom, and left sides independent of each other.

In the case of border-spacing, the spacing works in pairs, either horizontally or vertically. The following sets the horizontal space (the space between cells in adjacent columns) to 20px and the vertical space (the space between cells in adjacent rows) to 10px.

table { 
    border-spacing: 20px 10px;
    border-collapse: separate;
}

Ref: [1], [2]

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.

Tagged with:
, , , ,