HTML Tutorial menu

HTML Tables

Tables arrange data in rows and columns, like a timetable or a price list.

A Basic Table

TagMeaning
<table>The whole table
<tr>A table row
<th>A header cell (bold and centred by default)
<td>A normal data cell

Example

html
<!DOCTYPE html>
<html>
<body>

<table>
  <tr>
    <th>Item</th>
    <th>Price</th>
  </tr>
  <tr>
    <td>Tea</td>
    <td>Rs 80</td>
  </tr>
  <tr>
    <td>Paratha</td>
    <td>Rs 60</td>
  </tr>
</table>

</body>
</html>
Try it Yourself »

Each <tr> is one row. Each <th> or <td> inside it is one cell, from left to right.

Adding Borders

Tables have no borders by default. Add them with CSS. border-collapse: collapse joins the double lines into single lines.

Example

html
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
  border: 1px solid #999;
  border-collapse: collapse;
}
th, td {
  padding: 8px 12px;
}
th {
  background-color: #f2f2f2;
}
</style>
</head>
<body>

<table>
  <caption>Class Timetable</caption>
  <tr>
    <th>Day</th>
    <th>Subject</th>
    <th>Time</th>
  </tr>
  <tr>
    <td>Monday</td>
    <td>HTML</td>
    <td>4 pm</td>
  </tr>
  <tr>
    <td>Wednesday</td>
    <td>CSS</td>
    <td>4 pm</td>
  </tr>
</table>

</body>
</html>
Try it Yourself »

The <caption> tag gives the table a title. It must come straight after <table>.

Merging Cells

colspan makes a cell stretch across several columns. rowspan makes it stretch down several rows.

Example

html
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td { border: 1px solid #999; border-collapse: collapse; padding: 6px 10px; }
</style>
</head>
<body>

<table>
  <tr>
    <th>Name</th>
    <th colspan="2">Phone numbers</th>
  </tr>
  <tr>
    <td>Ali</td>
    <td>0300 0000000</td>
    <td>0321 0000000</td>
  </tr>
  <tr>
    <td rowspan="2">Ayesha</td>
    <td colspan="2">0333 0000000</td>
  </tr>
  <tr>
    <td colspan="2">0345 0000000</td>
  </tr>
</table>

</body>
</html>
Try it Yourself »

Table Sections

Bigger tables can be split into a head, a body and a foot. This helps screen readers and printing.

Example

html
<table>
  <thead>
    <tr><th>Month</th><th>Sales</th></tr>
  </thead>
  <tbody>
    <tr><td>January</td><td>Rs 50,000</td></tr>
    <tr><td>February</td><td>Rs 65,000</td></tr>
  </tbody>
  <tfoot>
    <tr><td>Total</td><td>Rs 115,000</td></tr>
  </tfoot>
</table>

Use tables only for data in rows and columns. Do not use them to lay out a whole page; use CSS Flexbox or Grid for that.

Exercise

Exercise

Which attribute makes a cell stretch across two columns?

Learn HTML with a teacher

Join the Web Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp