Skip to main content

HTML Table Headers

By SamK
0
0 recommends
Topic(s)

In HTML, tables can have headers for each column, each row, or for groups of columns or rows.

HTML Table Headers

Table headers are defined using <th> elements. Each <th> element represents a header cell in the table.

<table style=" width: 360px;">
  <tr>
    <th>Item</th>
    <th>Qty.</th>
    <th>Price</th>
  </tr>
  <tr>
    <td>Product</td>
    <td>1</td>
    <td>$10</td>
  </tr>
  <tr>
    <td>Product</td>
    <td>2</td>
    <td>$20</td>
  </tr>
</table>

In the above example, the first row is defined as the header of the table as you can see in the preview below. 

HTML Headers Demo

Vertical Table Headers

To use the first column as table header, you should define the first cell in each row as a <th> element.

<table style=" width: 360px;">
  <tr>
    <th>Item</th>
    <td>Product</td>
    <td>Product</td>
  </tr>
  <tr>
    <th>Qty.</th>
    <td>1</td>
    <td>2</td>
  </tr>
  <tr>
    <th>Price</th>
    <td>$10</td>
    <td>$20</td>
  </tr>
</table>

HTML Vertical Headers Demo

Align Table Headers

By default, table headers are bold and centered.

To align the table headers to the left, you can use the CSS text-align property.

th {
  text-align: left;
}

HTML Text-align Left Demo

Header for Multiple Columns

You can create a header that spans over two or more columns.

To achieve this, use the colspan attribute on the <th> element.

<table style=" width: 360px;">
                <tr>
                  <th colspan="2">Item & Qty.</th>
                  <th>Price</th>
                </tr>
                <tr>
                  <td>Product</td>
                  <td>1</td>
                  <td>$10</td>
                </tr>
                <tr>
                  <td>Product</td>
                  <td>2</td>
                  <td>$20</td>
                </tr>
            </table>

Header Multiple Column Demo

Table Caption

You can include a caption that acts as a heading for the entire table.

To add a caption to a table, you should use the <caption> tag.

<table style=" width: 360px;">
              <caption>Items with Quantity and Price</caption>
                <tr>
                  <th>Item</th>
                  <th>Qty.</th>
                  <th>Price</th>
                </tr>
                <tr>
                  <td>Product</td>
                  <td>1</td>
                  <td>$10</td>
                </tr>
                <tr>
                  <td>Product</td>
                  <td>2</td>
                  <td>$20</td>
                </tr>
            </table>

Table Caption Demo

Please check below options for the links to our previous or next tutorial.

Questions & Answers