So you have created table and now you are wondering how can you set cellspacing or cellpadding from CSS?
Luckily for us, CSS supports this functionality indeed, but name of the CSS properties are not that obvious and sometimes they are causing a bit of headache.
Example below shows table with cellpadding and cellspacing set using standard HTML attributes.
| Preview |
Code |
| First Cell |
Second Cell |
| Third Cell |
Fourth Cell |
| Fifth Cell |
|
<table width="200" cellspacing="2"
cellpadding="2" border="1">
<tr>
<td>First Cell</td>
<td>Second Cell</td>
</tr>
<tr>
<td>Third Cell</td>
<td>Fourth Cell</td>
</tr>
<tr>
<td colspan="2">Fifth Cell</td>
</tr>
</table>
|
Similar effect we can achive by removing attributes from table tag, and applying the effect from CSS. I used different colours to show the difference between table border and cell border.
| Preview |
Code |
| First Cell |
Second Cell |
| Third Cell |
Fourth Cell |
| Fifth Cell |
|
.myTable { width:200px; border-collapse:separate;
border-spacing:2px; }
.myTable td { border:1px solid red; }
.myTable { border:1px solid blue; }
|
As we can see in the example above, CSS property
border-collapse:separate; is separating cells from each other.
border-spacing:2px; sets the space between them.
Another handly value for
border-collapse; is
collapse which removes the spacing between the cells:
| Preview |
Code |
| First Cell |
Second Cell |
| Third Cell |
Fourth Cell |
| Fifth Cell |
|
.myTable { width:200px; border-collapse:collapse;
border-spacing:2px; }
.myTable td { border:1px solid red; }
.myTable { border:1px solid blue; }<table class="myTable"
style="border-collapse:collapse;">
<tr>
<td>First Cell</td>
<td>Second Cell</td>
</tr>
<tr>
<td>Third Cell</td>
<td>Fourth Cell</td>
</tr>
<tr>
<td colspan="2">Fifth Cell</td>
</tr>
</table>
|
As we can see this time any spacing between cells is automatically removed and so removed is external table border.
Is it better to use attributes or CSS? In my opinion - CSS. It is just a lot easier to change table look & feel from one CSS stylesheet instead of looking for the code in HTML document.
Post new comment