Styling HTML Table Headers: `` Element and CSS

Learn how to create and style effective table headers in HTML using the `` tag. This tutorial covers basic headers, vertical headers, alignment, headers spanning multiple columns, and adding table captions using ``. Includes clear examples and CSS styling techniques.



Creating and Styling HTML Table Headers

This chapter explains how to add and style table headers in HTML, enhancing the organization and readability of your tables.

Basic Table Headers

Table headers are created using the <th> (table header) element. These are typically displayed in bold and centered by default.

Example: Basic Table Headers

<table>
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
</table>
Output
            Firstname   Lastname   Age
Jill Smith 50

Vertical Headers

To use the first column as headers, make the first cell in each row a <th> element.

Example: Vertical Headers

<table>
  <tr>
    <th>Firstname</th>
    <td>Lastname</td>
    <td>Age</td>
  </tr>
  <tr>
    <th>Jill</th>
    <td>Smith</td>
    <td>50</td>
  </tr>
</table>

Aligning Headers

While headers are centered by default, you can change this using CSS text-align.

Example: Left-aligned Headers

th {
  text-align: left;
}

Headers Spanning Multiple Columns

The colspan attribute allows a header to span multiple columns.

Example: Header Spanning Columns

<table>
  <tr>
    <th colspan="2">Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
</table>

(More details on colspan are in the "Table colspan & rowspan" chapter.)

Adding a Table Caption

A table caption provides a title for the entire table. Use the <caption> tag immediately after the <table> tag.

Example: Table Caption

<table>
  <caption>Monthly Savings</caption>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
</table>