10. Tables in HTML

Tables

HTML tables allow web developers to arrange data into rows and columns.

  • <caption> tag is used for creating caption(table title).
  • <thead> to wrap table head
  • <tbody> to wrap table body
  • <tfoot> to wrap table footer
  • <tr> is to display table row.
  • <th> tag is for table header or first cells.
  • <td> tag is for table data or next cells.
  • Attributes:
    • align: to align the text inside the table.
      • To align a whole row, use this inside <tr> tag.
    • border: for border around table.
    • colspan="n": to create cells which spans over n COLOUMS
    • rowspan="n": to create cells which spans over n ROWS
  • Example:
<table border="1">
    <!-- caption -->
    <caption> Table subject </caption>
    <thead>
        <!-- Table Header -->
        <tr> 
            <td colspan="4" align="center"> MERGED COLOUMNS </td>
        </tr>
        <tr> 
            <th> Table Heading-> 1st coloumn </th>
            <th> Table Heading-> 2nd coloumn </th>
            <th> Table Heading-> 3rd coloumn </th>
            <th> Table Heading-> 4th coloumn </th>
        </tr>
    </thead>
    <tbody>
         <!-- Table Body -->
        <tr align="center" > 
            <td> 1st coloumn </td>
            <td> 2nd coloumn </td>
            <td> 3rd coloumn </td>
            <td rowspan="2"> 4th coloumn 2nd & 3rd row.</td>
        </tr>
        <tr> 
            <td> 1st coloumn </td>
            <td> 2nd coloumn </td>
            <td> 3rd coloumn </td>
            <!--4th coloumn filled by rowspan-->
        </tr>
    </tbody>
    <tfoot>
        <tr> 
            <td colspan="4" align="center"> FOOTER </td>
        </tr>
    </tfoot>
</table>
  • Preview:
    Table.png

More on Table:

Column Groups

  • You can use the <colgroup> and <col> elements to apply styles to an entire column in an HTML table.
<table>
  <colgroup>
    <col style="background-color:yellow">
  </colgroup>
  <!-- rest of the table -->
</table>

Accessibility in Tables

To make your tables more accessible, you can use the scope attribute in <th> elements to specify if they are headers for columns, rows, or groups of columns or rows.

<th scope="col">Name</th>
<th scope="col">Age</th>