.NET (296) administrative (41) Ajax (42) AngularJS (2) ASP.NET (145) bicycle (2) books (180) browser (8) C# (135) cars (1) chess (29) CodePlex (10) Coma (8) database (49) deployment (3) Entity Framework (2) essay (112) flash/shockwave (2) flex (1) food (3) friend (2) game (20) idea (5) IIS (8) javascript (83) LInQ (2) Linux (6) management (4) manga (43) misc (674) mobile (1) movies (91) MsAccess (1) murder (2) music (64) mysql (1) news (100) permanent (1) personal (68) PHP (1) physics (2) picture (309) places (12) politics (13) programming (507) rant (120) religion (3) science (43) Sharepoint (3) software (58) space (1) T4 (2) technology (11) Test Driven Development (4) translation (2) VB (2) video (98) Visual Studio (45) web design (46) Windows API (8) Windows Forms (3) Windows Server (6) WPF/Silverlight (63) XML (11)

Thursday, February 18, 2010

CSS cellpadding and cellspacing

There is one spiny issue when trying to move a html source from inline to CSS styling and that is the parameters of the table: cellspacing and cellpadding in particular.

From my tests it appears that cellpadding is overwritten by the CSS styling (the first time I ever see an inline attribute being overridden by CSS), however cellspacing does not. In order to remove the default cellspacing, use border-collapse:collapse on the table.

In order to set the table cellspacing through CSS, use the border of the td elements. Unfortunately, it doesn't work with transparent color, so you must set it to the color of the background. No luck if the background is an image. Margin on the cells doesn't work. Who uses cell spacing, anyway? Non Internet Explorer browsers have a table property called border-spacing, but it only works for some DOCTYPEs even in other browsers, so it's not reliable.

To set the table cell padding through CSS, just use the padding property of the cells. As I said earlier, it overrides the cellpadding property of the table.

So, in order to set 5px cell spacing and 5px cell padding through CSS, use this:
 body {
background-color:white; /* use the same color for the border of cells */
}
table {
border-collapse:collapse; /* remove default cellspacing */
border-spacing:5px; /* it works on some browsers on some DOCTYPEs */
}
td {
padding:5px; /* cell padding */
border:5px solid white; /* cell spacing */
}


You should set the padding as a general rule for all the TDs on the page. CSS classes like
table.MyClass td { padding:1px }
will affect all cells in all child tables! The more general the CSS selector, the easier will be to avoid overwriting some of your normal settings. For example, the CSS rule above would override
.myTD { padding-right:3px; }
because it is more specific.

No comments: