HTML Tables

HTML Tables are used to arrange data into rows and columns.

They are used to display a list of data in a tabular form, which can be anything like product listing, inventory listing, orders, reports, etc.,

Here is a list of HTML elements used to define a table and its components.

  • Element <table> to define a table
  • Element <tr> to define a row
  • Element <td> to define a cell
  • Element <th> to define a header cell

Syntax

The basic syntax looks like the one below.

<table>...</table>

Table with rows

<table>
    <tr>...</tr>
    <tr>...</tr>
</table>

Table with both rows and columns

<table>
    <tr>
        <td>...</td>
        <td>...</td>
    </tr>
    <tr>
        <td>...</td>
        <td>...</td>
    </tr>
</table>

HTML Table with both rows and columns

The below example contains both rows and columns.

<table>
    <tr>
        <th>Product</th>
        <th>Sales</th>
    </tr>
    <tr>
        <td>Bread</td>
        <td>10000</td>
    </tr>
    <tr>
        <td>Butter</td>
        <td>3000</td>
    </tr>
</table>

Spanning Multiple Rows and Columns

The below elements can be used to span a row or a column to multiple cells.

  • Element <colspan> to span a cell to multiple columns
  • Element <rowspan> to span a row to multiple rows
<table>
    <tr>
        <th>Name</th>
        <th colspan="2">Address</th>
    </tr>
    <tr>
        <td>Arun</td>
        <td>ABC 123 STREET</td>
        <td>XYZ 123 STREET</td>
    </tr>
</table>
<table>
    <tr>
        <th>Name</th>
        <th>Arun</th>
    </tr>
    <tr>
        <td rowspan="2">Address</td>
        <td>ABC 123 STREET</td>
    </tr>
    <tr>
        <td>XYZ 123 STREET</td>
    </tr>
</table>

Table Caption

The element <caption> can be used to give a title to a table as shown below.

<table>
    <caption>Product Details</caption>
    <tr>...</tr>
    <tr>...</tr>
    <tr>...</tr>
</table>

Defining Table Header, Body, and Footer

The below example contains the below elements to define the header, body and footer elements of a table.

  • Element <thead> defines a table header
  • Element <tbody> defines a table body
  • Element <tfoot> defines a table footer

These are used to create a more structured table with a row encapsulated within a header element, another within a footer element, and the rest within the body element.

<table>
    <thead>
        <tr>
            <th>Product</th>
            <th>Sales</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Bread</td>
            <td>10000</td>
        </tr>
        <tr>
            <td>Butter</td>
            <td>3000</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td>Totals</td>
            <td>13000</td>
        </tr>
    </tfoot>
</table>

Overall

HTML Tables play an important role in organizing the content in a tabular form.

Related Links