Cellpadding Spacing - HTML Tutorial
The <table> element is used to organize data in rows and columns. In the past, HTML offered attributes like border, cellpadding, and cellspacing to control spacing around table cells. Today, these are considered obsolete, and CSS provides a cleaner and more flexible way to style tables. For learning purposes, we’ll first demonstrate the old attributes, then show the modern CSS approach.
Let’s start by creating a simple table with no borders or spacing. To make things easier to see, we’ll color the table background green and the individual table cells yellow.
<!DOCTYPE html>
<html>
<head>
<style>
table {
background-color: #009900;
border-collapse: collapse; /* ensures cells share borders if set */
}
td {
background-color: #ffff00;
}
</style>
</head>
<body>
<table>
<tr>
<td>Left Cell</td>
<td>Middle Cell</td>
<td>Right Cell</td>
</tr>
</table>
</body>
</html>
With no borders or spacing, the cells are cramped and the table’s green background is mostly hidden. Let’s add spacing using CSS instead of HTML attributes.
<!DOCTYPE html>
<html>
<head>
<style>
table {
background-color: #009900;
border-collapse: separate; /* enables spacing between cells */
border-spacing: 10px; /* spacing between cells */
border: 5px solid #009900; /* table border */
}
td {
background-color: #ffff00;
padding: 20px; /* space inside each cell */
}
</style>
</head>
<body>
<table>
<tr>
<td>Left Cell</td>
<td>Middle Cell</td>
<td>Right Cell</td>
</tr>
</table>
</body>
</html>
Here’s what the CSS does:
- border: creates a 5-pixel border around the table.
- padding: adds 20 pixels of space inside each cell, making the content more readable.
- border-spacing: separates the cells from each other by 10 pixels, allowing the table background to show through.
This modern approach using CSS is preferred because it separates content from presentation, gives you more control, and works consistently across all modern browsers.
