Loading lessons...
Advanced Tables
You already know the basics. Now let's make tables beautiful and powerful!
Table borders
By default, tables have no visible borders. Add them with CSS:
css
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
border-collapse: collapse makes the double borders become one clean border.
Table sizes
Set the width of a table, and the height of rows:
css
table {
width: 100%;
}
th {
height: 50px;
}
Column widths
css
th, td {
width: 25%;
}
Padding and spacing
padding: space INSIDE cells.border-spacing: space BETWEEN cells (when borders aren't collapsed).
css
th, td {
padding: 15px;
}
Header styling
Style the header row with a background color:
css
th {
background-color: #04AA6D;
color: white;
}
Zebra stripes
Color alternate rows so they're easy to read:
css
tr:nth-child(even) {
background-color: #f2f2f2;
}
Hover highlight
Light up a row when the mouse hovers over it:
css
tr:hover {
background-color: #ddd;
}
Colgroup: style whole columns
Use <colgroup> and <col> to style a whole column at once:
html
<table>
<colgroup>
<col span="2" style="background-color: lightblue;">
<col style="background-color: lightgreen;">
</colgroup>
<tr>
<th>Name</th>
<th>Score</th>
<th>Grade</th>
</tr>
</table>
span="2" means "apply this style to 2 columns."
A full fancy table
html
<style>
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
tr:nth-child(even) { background-color: #f2f2f2; }
th { background-color: #04AA6D; color: white; }
</style>
<table>
<tr>
<th>Name</th>
<th>City</th>
<th>Score</th>
</tr>
<tr>
<td>Ada</td>
<td>London</td>
<td>95</td>
</tr>
<tr>
<td>Linus</td>
<td>Helsinki</td>
<td>88</td>
</tr>
</table>
TL;DR
- Borders:
border+border-collapse: collapse. - Size:
widthon the table,heighton rows. - Space:
paddinginside cells. - Zebra stripes:
tr:nth-child(even). - Hover:
tr:hover. <colgroup>/<col>style whole columns.