BLOGS BY TOPIC
BLOGS BY AUTHOR
BLOGS BY YEAR
This is the second of a three-part online training series of blogs on CSS style sheets. This blog shows how to create styles for specific HTML tags (the first part covers the principles of CSS style sheets, and the third part gives a worked example of CSS).
- CSS Styles for Specific HTML Tags
- Block Elements (Heading, Div and Paragraph Tags)
- Inline Tags - Span, Em and Strong
- Styling Images - the IMG Tag
- Styles for Ordered and Unordered Lists - ul, ol and li
- Hyperlinks (the A Tag)
- Table Styles (this blog)
- Setting CSS for Other Tags in HTML
Posted by Andy Brown on 16 May 2012
You need a minimum screen resolution of about 700 pixels width to see our blogs. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.
Before I begin to talk about table styles, it's worth mentioning something which is often-repeated, and always true.
Tables in CSS should be used only to list rows and columns of data, and not for laying out pages (for which the float attribute should be used).
The Table Tags in HTML
The main table tags are as follows:
|Tag||What it does|
|table||Introduces a table|
|tr||Introduces a row in a table|
|td||Introduces a cell in a table|
|th||A header cell|
Our Example Table
Here's an example of a table, before and after applying styles:
|Without styles||With CSS styles as below|
The HTML for this (with indentation applied to make it easier to read) is:
The HTML contains 3 rows: a row of headings and two rows of data. The entire table is included in a div tag with class divTable.
Creating Styles for a Table
Here are the styles for the table above:
/* class containing some tables */
/* ensure space above and below table */
margin: 20px 0;
/* table heading cells within class */
.divTable table th
border: 1px solid #000;
/* normal table cells within class */
.divTable table td
border: 1px solid #000;
So, for example, table cells which lie within a table within the divTable class will be formatted with a 1 pixel border and 5 pixels padding.
The CellSpacing Attribute in Tables
You can (and probably should - see below) use a table's cellspacing attribute:
|With cellspacing set to 0||Without cellspacing set|
There is a CSS alternative to the cellspacing tag using border-spacing, but it's not supported by Internet Explorer and requires lots of fiddly adjustments to work perfectly. Make your life easier and just use the cellspacing table attribute (this is one of the few times when you should include formatting within HTML).
Here is the HTML setting the cellspacing attribute (you can set it to any number of pixels):
By setting the cell spacing to 0, you eliminate any spacing between cells.
Note that a table also has a cellpadding attribute, giving the padding round cells, but this is easily reproduced using the CSS padding style.