DEV Community

Cover image for HTML : Apply cellpadding and cellspacing to table with and without using CSS
Rajesh Kumar Yadav
Rajesh Kumar Yadav Subscriber

Posted on

9 1

HTML : Apply cellpadding and cellspacing to table with and without using CSS

What is Cellpadding?

Cellpadding - Sets the amount of space between the contents of the cell and the cell wall

What is Cellspacing?

Cellspacing - Controls the space between table cells

Old school way of setting cellpadding and cellspacing is like this:



<table cellspacing="1" cellpadding="1">


Enter fullscreen mode Exit fullscreen mode

But there are various way to achieve the same.

Method 1

For controlling "cellpadding" in CSS, you can simply use padding on table cells. E.g. for 10px of "cellpadding":



td { 
    padding: 10px;
}


Enter fullscreen mode Exit fullscreen mode

For "cellspacing", you can apply the border-spacing CSS property to your table. E.g. for 10px of "cellspacing":



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


Enter fullscreen mode Exit fullscreen mode

This property will even allow separate horizontal and vertical spacing, something you couldn't do with old-school "cellspacing".

Method 2

The default behavior of the browser is equivalent to:



table {border-collapse: collapse;}
td    {padding: 0px;}


Enter fullscreen mode Exit fullscreen mode

Alt Text

Set Cellpadding

To set this we need set the padding to td



table {border-collapse: collapse;}
td    {padding: 6px;}


Enter fullscreen mode Exit fullscreen mode

So that it will look like as -
Alt Text

Set Cellspacing

To set this we need to set border-spacing to table



table {border-spacing: 2px;}
td    {padding: 0px;}


Enter fullscreen mode Exit fullscreen mode

So that it will look like as -
Alt Text

Setting Cellspacing and Cellspacing both



table {border-spacing: 8px 2px;}
td    {padding: 6px;}


Enter fullscreen mode Exit fullscreen mode

So that it will look like as -
Alt Text



table {border-spacing: 2px;}
td    {padding: 6px;}


Enter fullscreen mode Exit fullscreen mode

So that it will look like as -
Alt Text

Summary



table
{
    border-collapse: collapse; /* 'cellspacing' equivalent */
}

table td, table th
{
    padding: 0; /* 'cellpadding' equivalent */
}


Enter fullscreen mode Exit fullscreen mode

Buy Me A Coffee

With all that being said, I highly recommend you keep learning!

Thank you for reading this article. Please feel free to connect with me on LinkedIn and Twitter.

Top comments (0)

šŸ‘‹ Kindness is contagious

Please leave a ā¤ļø or a friendly comment on this post if you found it helpful!

Okay