Skip to content

HTML Tables

HTML tables are used to display data in a grid format of rows and columns. Tables are very useful for displaying structured data such as financial reports, student grades, product comparisons, etc.

Basic Table Structure

A basic HTML table consists of the following core tags:

  • <table>: Defines the container for the entire table.
  • <tr> (Table Row): Defines a row in the table.
  • <td> (Table Data): Defines a cell. Cells are where data is placed.

Example:

html
<table>
  <tr>
    <td>Cell 1.1</td>
    <td>Cell 1.2</td>
  </tr>
  <tr>
    <td>Cell 2.1</td>
    <td>Cell 2.2</td>
  </tr>
</table>

By default, tables have no borders. You need to use CSS to add borders and other styles.

css
table, th, td {
  border: 1px solid black;
  border-collapse: collapse; /* Merge borders */
}
th, td {
  padding: 8px; /* Add padding */
}

Table Headers <th>

The <th> (Table Header) tag is used to define header cells. It's used similarly to <td>, but its content semantically represents the heading for that column or row.

Browsers typically display <th> content in bold and centered.

html
<table>
  <tr>
    <th>Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>John</td>
    <td>25</td>
  </tr>
  <tr>
    <td>Jane</td>
    <td>30</td>
  </tr>
</table>

Spanning Rows and Columns

Sometimes, a cell needs to span multiple rows or columns. This can be achieved using the rowspan and colspan attributes.

  • colspan (Column Span): Makes a cell span a specified number of columns.
  • rowspan (Row Span): Makes a cell span a specified number of rows.

Example:

html
<table>
  <tr>
    <th>Name</th>
    <th colspan="2">Contact Info</th>
  </tr>
  <tr>
    <td>John</td>
    <td>Phone</td>
    <td>12345</td>
  </tr>
  <tr>
    <td rowspan="2">Jane</td>
    <td>Phone</td>
    <td>67890</td>
  </tr>
  <tr>
    <td>Email</td>
    <td>jane@example.com</td>
  </tr>
</table>

More Semantic Table Structure

To make the table structure clearer, especially for complex tables, HTML provides <thead>, <tbody>, and <tfoot> tags to define the table's header, body, and footer respectively.

  • <thead>: Wraps the header row(s) (<tr> containing <th>).
  • <tbody>: Wraps the main data rows of the table.
  • <tfoot>: Wraps the footer or summary row(s).

These three tags help browsers and assistive technologies (like screen readers) better understand the table structure. A table can have only one <thead> and one <tfoot>, but can have multiple <tbody> sections.

html
<table>
  <thead>
    <tr>
      <th>Product</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Apple</td>
      <td>$1</td>
    </tr>
    <tr>
      <td>Banana</td>
      <td>$0.5</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Total</td>
      <td>$1.5</td>
    </tr>
  </tfoot>
</table>

Content is for learning and research only.