HTML cellspacing Attribute: A Step-by-Step Guide with Examples and Best Practices

The cellspacing attribute in HTML defines the space between table cells. It was widely used in older versions of HTML but is now considered outdated in favor of CSS.

🔹 Note: The cellspacing attribute is deprecated in HTML5. The preferred method is using the border-spacing CSS property.

Step-by-Step Guide to Using cellspacing in HTML

Step 1: Basic Table Without cellspacing

By default, an HTML table has no extra space between its cells.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML Table Without Cellspacing</title>
</head>
<body>
    <table border="1">
        <tr>
            <td>Cell 1</td>
            <td>Cell 2</td>
        </tr>
        <tr>
            <td>Cell 3</td>
            <td>Cell 4</td>
        </tr>
    </table>
</body>
</html>

🔹 Output: A basic table with no extra spacing between cells.

Step 2: Adding cellspacing to a Table

The cellspacing attribute increases the space between the table cells.

<table border="1" cellspacing="10">
    <tr>
        <td>Cell 1</td>
        <td>Cell 2</td>
    </tr>
    <tr>
        <td>Cell 3</td>
        <td>Cell 4</td>
    </tr>
</table>

🔹 Explanation:

  • cellspacing="10" adds 10 pixels of space between table cells.

🔹 Output: The table cells now have extra space between them.

Best Practices & Modern Alternatives

Since cellspacing is deprecated in HTML5, you should use CSS instead.

Step 3: Using border-spacing in CSS (Recommended)

<style>
    table {
        border-collapse: separate;
        border-spacing: 10px; /* Space between cells */
    }
</style>

<table border="1">
    <tr>
        <td>Cell 1</td>
        <td>Cell 2</td>
    </tr>
    <tr>
        <td>Cell 3</td>
        <td>Cell 4</td>
    </tr>
</table>

🔹 Key Differences:
border-spacing works like cellspacing, but is more flexible.
border-collapse: separate; ensures spacing works correctly.
✅ CSS is the modern way to handle spacing in tables.

Common Mistakes to Avoid

Using cellspacing in HTML5 (deprecated).
Use border-spacing in CSS instead.

Forgetting border-collapse: separate;
✅ Without it, border-spacing may not work as expected.