Tables Css - HTML Tutorial
For precise control over borders, spacing, and padding in tables, CSS is the preferred method. Modern browsers fully support these CSS properties, making the old cellpadding and cellspacing attributes largely obsolete. For legacy support, you can still include those attributes, but CSS should be your primary tool for styling.
The key CSS properties for table layout are:
padding- sets the inner spacing of table cells, replacing the oldcellpaddingattribute.border-spacing- sets the spacing between table cells, replacing the oldcellspacingattribute.border- defines the border of the table or cells, replacing the oldborderattribute.
CSS allows you to use any valid length unit such as px, em, rem, or %. In our examples, we’ll use pixels for simplicity.
<head>
<style>
table {
background: #009900;
border: 4px #ff00ff ridge;
border-spacing: 5px;
}
td {
background: #ffff00;
padding: 10px;
border: 2px #0000ff dotted;
}
td.middle {
border: 2px #ff0000 solid;
padding-right: 25px;
}
</style>
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" summary="Table with CSS borders">
<tr>
<td>Left Cell</td>
<td class="middle">Middle Cell</td>
<td>Right Cell</td>
</tr>
</table>
</body>
In this example:
- The table has a green background and a lavender ridged border. Your own styling will likely be more subtle and visually appealing.
- Regular table cells have a yellow background, 10 pixels of padding, 5 pixels of spacing between cells, and a blue dotted border.
- Cells with
class="middle"have an extra 15 pixels of padding on the right and a solid red border.
Modern browsers fully support these CSS properties. Using CSS for primary styling ensures consistent appearance across devices and resolutions, while older table attributes can be included as fallback for legacy systems if absolutely necessary.
