10

HTML – Tables

Chapter 10 • Intermediate

25 min

Tables let you display data in rows and columns, similar to a spreadsheet.

Basic table structure

Main tags used in a table:

  • <table> – wraps the entire table.
  • <tr> – table row.
  • <th> – header cell (usually bold and centered).
  • <td> – normal data cell.

Example:

<table>

<tr>

<th>Name</th>

<th>Age</th>

</tr>

<tr>

<td>Amit</td>

<td>22</td>

</tr>

</table>

Adding a caption and grouping content

More advanced tags:

  • <caption> – title for the table.
  • <thead> – groups header rows.
  • <tbody> – groups main body rows.
  • <tfoot> – groups footer rows.

These help with structure, styling, and accessibility.

Attributes and styling

Old attributes like border, cellpadding, and cellspacing used to control appearance:

  • border – width of the border.
  • cellpadding – space between cell content and cell border.
  • cellspacing – space between cells.

In modern HTML, it is better to control all styling with CSS instead:

  • border: 1px solid #000;
  • border-collapse: collapse;
  • padding: 8px;

Merging cells

You can combine cells:

  • colspan – merge cells horizontally.
  • rowspan – merge cells vertically.

Example:

  • <th colspan="2">Personal Info</th>
  • <td rowspan="2">Jane</td>

When to use tables

Use tables for:

  • Tabular data like reports, schedules, comparison charts.

Do not use tables for page layout. Use CSS layout (flexbox, grid) for that.

Suggested image prompt

"Table example mockup comparing students (name, age, city) with header row, caption, and one cell using colspan, visually labeled with <table>, <tr>, <th>, <td> annotations."

Interview-style questions from this topic

  1. Which tags are used to create a basic HTML table?
  2. What is the difference between <th> and <td>?
  3. What is the purpose of <thead>, <tbody>, and <tfoot>?
  4. How do colspan and rowspan work? Give an example of each.
  5. Why should tables not be used for page layout in modern web development?

Hands-on Examples

Basic Table Example

<!DOCTYPE html>
<html>
<head>
  <title>Basic Table Example</title>
</head>
<body>
  <h1>Basic Table</h1>
  <table border="1">
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>City</th>
    </tr>
    <tr>
      <td>John</td>
      <td>25</td>
      <td>New York</td>
    </tr>
    <tr>
      <td>Jane</td>
      <td>30</td>
      <td>London</td>
    </tr>
  </table>
</body>
</html>

This is a simple table with one header row and two data rows. The <th> elements define the column headings, and the <td> elements contain the actual data. The border attribute quickly adds visible borders, though in real projects you would typically use CSS for styling.