HTMLLesson 6 of 10Jump to practice
Tables
Show data in rows and columns with table, tr, th and td.
Use a table when your data has rows and columns, like a timetable, a price list or exam results.
| Element | Meaning |
|---|---|
<table> |
The whole table |
<tr> |
A table row |
<th> |
A header cell (bold and centered by default) |
<td> |
A data cell |
<caption> |
A title for the table |
A table is built row by row. Each <tr> holds its cells from left to right.
<!DOCTYPE html>
<html>
<head>
<style>
table { border-collapse: collapse; }
th, td { border: 1px solid #999; padding: 6px 12px; }
</style>
</head>
<body>
<table>
<caption>Class test results</caption>
<tr>
<th>Name</th>
<th>English</th>
<th>Math</th>
</tr>
<tr>
<td>Emma</td>
<td>78</td>
<td>91</td>
</tr>
<tr>
<td>Diego</td>
<td>85</td>
<td>74</td>
</tr>
</table>
</body>
</html>Tables have no borders by default. The small <style> block above adds them. You’ll learn how that works in the CSS course.
Header, body and footer sections
Larger tables group their rows into <thead>, <tbody> and <tfoot>. This doesn’t change how the table looks, but it tells the browser which rows are headings and which are totals.
Cells that span
colspan="2" makes a cell two columns wide. rowspan="2" makes it two rows tall.
<!DOCTYPE html>
<html>
<head>
<style>
table { border-collapse: collapse; }
th, td { border: 1px solid #999; padding: 6px 12px; text-align: left; }
tfoot { font-weight: bold; }
</style>
</head>
<body>
<table>
<thead>
<tr><th>Item</th><th>Price</th></tr>
</thead>
<tbody>
<tr><td>Notebook</td><td>$3</td></tr>
<tr><td>Pen</td><td>$1</td></tr>
</tbody>
<tfoot>
<tr><td colspan="2">Total: $4</td></tr>
</tfoot>
</table>
</body>
</html>Practice
Check what you just learned. Fill in the missing code, then answer the quiz.
Exercise 1Solved
Each row of a table uses one element. Fill it in.
<table> <> <td>Apple</td> <td>$1.25</td> </> </table>Short for table row.
Exercise 2Solved
Make these header cells, so browsers and screen readers know they label the columns.
<tr> <>Fruit</> <th>Price</th> </tr>Exercise 3Solved
Make this cell stretch across two columns.
<tr> <td ="2">Total: 240</td> </tr>Short for column span.
Finish the practice to complete this lesson.
Sign in to keep your progress on any device.