Remove cellpadding and cellspacing from an HTML table with CSS
Posted November 5th, 2008 in HTML and CSS
The pre-CSS way to remove cellpadding and cellspacing from tables was to set the table cellpadding and cellspacing attributes to zero. However it's a nuisance to have to do this to all tables and it's easier to do this with CSS. This post looks at how to remove the default padding and spacing from an HTML table with CSS.
Our example table looks like this:
<table>
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>
and with some basic style so we can see the spacing and padding:
table {
border: 1px solid black;
}
td {
background-color: #ccc;
}
This results in a table with the default amount of cellpadding and cellspacing as shown in the example screenshot below. The spacing can be seen between the grey background of the cells and the black border.

Without any use of CSS to get rid of the cellpadding and spacing you would do this:
<table cellspacing="0" cellpadding="0">
and this would result in the table now looking like this:

To do this with CSS alone, leave the <table> tag as-is and add the following definitions to the CSS style sheet:
table {
border-collapse: collapse;
}
th, td {
padding: 0;
}
The border-collapse table definition gets rid of the spacing and the padding in this instance removes all padding from a cell. Often you will still want padding (our example above makes the data difficult to read with no padding) but this way you can style the default amount of padding yourself separately from the table in the style sheet, and can apply it to either all tables or particular classes or #elements.
Related posts:
- Style an HTML form input with CSS and jQuery (Saturday, July 26th 2008)
- Targeting specific versions of Internet Explorer and other browsers with conditional comments (Wednesday, June 18th 2008)
- Internet Explorer 8's compatibility flags (Friday, May 30th 2008)
- Using Internet Explorer Conditional Tags for Style Sheet Selection (Wednesday, May 21st 2008)
- Centering a page with HTML and CSS (Tuesday, May 6th 2008)
Recent posts:
- MySQL queries for article summaries part 2 of 2 (Tuesday, January 6th 2009)
- Aims for 2009 (Monday, January 5th 2009)
- Weekly Roundup - January 5th 2008 (Monday, January 5th 2009)
- MySQL queries for article summaries part 1 of 2 (Sunday, January 4th 2009)
- 2008 Summary of Posts (Saturday, January 3rd 2009)
- 2008 / 2009 overview (Friday, January 2nd 2009)
Subscribe to RSS Feed / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email and have my posts sent in a daily email.
Posts are made using the following schedule (although it may vary some weeks): Mondays & Fridays = PHP; Tuesdays & Saturdays = MySQL; Wednesdays & Sundays = Javascript/jQuery; Thursdays = HTML/CSS.
