HTML Table Headers

      Comments Off on HTML Table Headers
Spread the love

HTML tables are commonly used for displaying tabular data in a structured manner. Tables are made up of rows and columns, and often include table headers to provide additional information about the data. In this article, we’ll discuss HTML table headers and how they can be used to enhance the readability and organization of tables.

Vertical Table Headers

By default, HTML table headers are displayed horizontally at the top of each column. However, it is also possible to display headers vertically along the side of a table. This can be achieved using the scope attribute with a value of "row" or "col", depending on the orientation of the header. For example:

html
<table>
  <thead>
    <tr>
      <th scope="col">Product</th>
      <th scope="col">Price</th>
      <th scope="col">Quantity</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">Apples</th>
      <td>$1.00</td>
      <td>10</td>
    </tr>
    <tr>
      <th scope="row">Bananas</th>
      <td>$0.50</td>
      <td>20</td>
    </tr>
  </tbody>
</table>

In the example above, the first column headers are displayed vertically using the scope attribute with a value of "row". This makes it easier for the user to associate each row with its corresponding product.

Aligned Table Headers

Another way to enhance the organization of table headers is to align them with their corresponding data. This can be achieved using the align attribute with a value of "left", "center", or "right". For example:

html
<table>
  <thead>
    <tr>
      <th align="left">Product</th>
      <th align="center">Price</th>
      <th align="right">Quantity</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td align="left">Apples</td>
      <td align="center">$1.00</td>
      <td align="right">10</td>
    </tr>
    <tr>
      <td align="left">Bananas</td>
      <td align="center">$0.50</td>
      <td align="right">20</td>
    </tr>
  </tbody>
</table>

In the example above, each header is aligned with its corresponding data using the align attribute. This helps to visually organize the table and makes it easier for the user to read.

Multiple Table Headers

In some cases, a table may require multiple levels of headers to provide additional information about the data. This can be achieved using the th element with the scope attribute set to "colgroup" or "rowgroup". For example:

html
<table>
  <thead>
    <tr>
      <th rowspan="2">Product</th>
      <th colspan="2">Price</th>
    </tr>
    <tr>
      <th>Regular</th>
      <th>Sale</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">Apples</th>
      <td>$1.00</td>
      <td>$0.90</td>
    </tr>
    <tr>
      <th scope="row">Bananas</th>
      <td>$0.50</td>
      <td>$0.40</td>