HTML Tables

Learn how to display structured data on web pages using HTML tables.

What are HTML Tables?

HTML Tables are used to display tabular data — data organized in rows and columns.

Real-Life Example: Just like an Excel sheet, HTML tables organize information in rows and columns for easy reading.

Table Structure

  • <table> – The container for the table
  • <caption> – Table title (optional)
  • <tr> – Table row
  • <th> – Table header cell
  • <td> – Table data cell

Tip: Use <th> for headers to improve accessibility and screen reader support.

Example: Basic HTML Table

HTML Code:


<table border="1">
    <caption>Student Scores</caption>
    <tr>
        <th>Name</th>
        <th>Math</th>
        <th>Science</th>
    </tr>
    <tr>
        <td>Alice</td>
        <td>95</td>
        <td>88</td>
    </tr>
    <tr>
        <td>Bob</td>
        <td>78</td>
        <td>85</td>
    </tr>
</table>

                

Output on browser:

Student Scores
Name Math Science
Alice 95 88
Bob 78 85

Advanced Table Features

  • colspan – Merge cells horizontally
  • rowspan – Merge cells vertically
  • thead, tbody, tfoot – For better structure and styling
  • Use CSS for styling instead of border attribute

Example: Merged Cells


<table border="1">
    <tr>
        <th>Name</th>
        <th colspan="2">Scores</th>
    </tr>
    <tr>
        <td>Alice</td>
        <td>Math: 95</td>
        <td>Science: 88</td>
    </tr>
</table>

                

Best Practices for HTML Tables

  • Use <th> for headers, not <td>
  • Always include a <caption> for accessibility
  • Use semantic grouping with thead, tbody, tfoot
  • Keep tables readable and not overly complex
  • Use CSS for styling rather than HTML attributes like border

Pro Tip: Properly structured tables improve accessibility for screen readers and enhance user experience.