HTML Tables

HTML tables display data in rows and columns. A table is built with <table>, rows with <tr>, header cells with <th> and data cells with <td>. Use tables for tabular data, not for page layout.

A Basic HTML Table

Without CSS a table has no borders. border-collapse merges the double borders into single lines.

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Table</title>
<style>table, th, td { border: 1px solid #999; border-collapse: collapse; padding: 6px 10px; }</style></head>
<body>
  <table>
    <tr><th>Product</th><th>Price</th></tr>
    <tr><td>Green Tea</td><td>$6.00</td></tr>
    <tr><td>Olive Oil</td><td>$18.75</td></tr>
  </table>
</body>
</html>

Captions and Table Sections

<caption> gives the table a title. <thead>, <tbody> and <tfoot> group header, body and footer rows, which helps accessibility and styling.

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Sections</title>
<style>
  table { border-collapse: collapse; } th, td { border: 1px solid #ccc; padding: 6px 12px; }
  thead { background: #1e3a8a; color: white; } tfoot { font-weight: bold; }
  tbody tr:nth-child(even) { background: #f1f5f9; }
</style></head>
<body>
  <table>
    <caption>Monthly expenses</caption>
    <thead><tr><th scope="col">Item</th><th scope="col">Cost</th></tr></thead>
    <tbody>
      <tr><td>Rent</td><td>500</td></tr>
      <tr><td>Food</td><td>200</td></tr>
      <tr><td>Internet</td><td>30</td></tr>
    </tbody>
    <tfoot><tr><td>Total</td><td>730</td></tr></tfoot>
  </table>
</body>
</html>

colspan and rowspan

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

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Spans</title>
<style>td, th { border: 1px solid #888; padding: 6px; text-align: center; } table { border-collapse: collapse; }</style></head>
<body>
  <table>
    <tr><th colspan="3">Weekly Timetable</th></tr>
    <tr><td rowspan="2">Monday</td><td>9:00</td><td>Maths</td></tr>
    <tr><td>11:00</td><td>Science</td></tr>
  </table>
</body>
</html>

Accessible Tables

  • Use <th> for header cells, never bold <td> cells
  • Add scope="col" or scope="row" to headers in larger tables
  • Give every data table a <caption>
  • Wrap wide tables in a container with overflow-x: auto so they scroll on phones

Frequently asked questions

How do I add a border to an HTML table?

Use CSS: table, th, td { border: 1px solid black; border-collapse: collapse; }. The old border attribute is obsolete.

Should I use tables for page layout?

No. Use CSS Flexbox or Grid for layout. Tables are meant for tabular data and layout tables confuse screen readers.

How do I merge cells in an HTML table?

Use colspan to merge horizontally and rowspan to merge vertically, then remove the cells that the span replaces.