Chapter 10 of 26

Tables

Some information naturally has rows and columns: a marks sheet, a class timetable, a comparison of laptops, the truth table of a logic gate. A list can't show this clearly, because each item has several related values. For this kind of tabular data, HTML gives us tables.

In this chapter, we'll build tables from scratch, add headers and captions, group rows into a head, body and foot, merge cells with colspan and rowspan, make tables accessible, and add basic styling with CSS.

What Is an HTML Table?

An HTML table (<table>) represents data in a two-dimensional grid. It is built row by row: each table row (<tr>) contains cells, which are either header cells (<th>) or data cells (<td>).

The key idea is that HTML tables are written one row at a time. There is no “column” element that holds cells — columns are formed by cells lining up in successive rows.

<table>
  <tr>
    <th>Name</th>
    <th>Marks</th>
  </tr>
  <tr>
    <td>Aisha</td>
    <td>86</td>
  </tr>
  <tr>
    <td>Rahul</td>
    <td>74</td>
  </tr>
</table>

In the browser:

 Name    Marks
 Aisha   86
 Rahul   74

By default there are no borders. <th> cells are bold and centred; <td> cells are normal weight and left-aligned. We'll add borders with CSS shortly.

ElementStands forPurpose
<table>tableWraps the whole table
<tr>table rowOne horizontal row
<th>table headerA heading cell for a column or row
<td>table dataAn ordinary data cell
<caption>captionThe table's title
<thead>, <tbody>, <tfoot>head, body, footGroup rows into sections

Header Cells and the scope Attribute

Use <th> for any cell that labels other cells — not just because you want bold text. Headers can label a column, a row, or both.

The scope attribute says which cells a header labels:

scopeThe header applies to…
colThe cells below it in its column
rowThe cells to its right in its row
colgroupA group of columns (used with <colgroup>)
rowgroupA group of rows (e.g. a whole <tbody>)
<table>
  <tbody>
    <tr>
      <th scope="col">Student</th>
      <th scope="col">DSA</th>
      <th scope="col">OS</th>
    </tr>
    <tr>
      <th scope="row">Aisha</th>
      <td>86</td>
      <td>91</td>
    </tr>
  </tbody>
</table>

Why bother? A sighted user glances up and left to know that “91” is Aisha's OS mark. A screen-reader user can't glance. With proper headers, a screen reader can announce “Aisha, OS, 91” when the user moves to that cell. For simple tables browsers can often guess, but scope removes the guesswork.


Captions

<caption> gives the table a title. It must be the first child of <table>. Browsers show it centred above the table.

<table>
  <caption>Internal Assessment Marks – Semester 3</caption>
  <tbody>
    <tr>
      <th scope="col">Student</th>
      <th scope="col">Marks</th>
    </tr>
    <tr>
      <td>Aisha</td>
      <td>86</td>
    </tr>
  </tbody>
</table>

A caption helps everyone: screen readers announce it when the user reaches the table, so they can decide whether to explore or skip it.


Row Groups: <thead>, <tbody>, <tfoot>

Larger tables are divided into three sections:

  • <thead> – the header row(s).
  • <tbody> – the main data rows. A table may have several <tbody> elements to group related rows.
  • <tfoot> – summary rows such as totals or averages.
<table>
  <caption>Monthly Expenses</caption>
  <thead>
    <tr>
      <th scope="col">Item</th>
      <th scope="col">Amount (₹)</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Hostel rent</td>
      <td>4500</td>
    </tr>
    <tr>
      <td>Mess</td>
      <td>3200</td>
    </tr>
    <tr>
      <td>Books</td>
      <td>800</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <th scope="row">Total</th>
      <td>8500</td>
    </tr>
  </tfoot>
</table>

Why use them?

  • Meaning: the browser and assistive technologies know which rows are headers and which are totals.
  • Styling: CSS can target thead or tfoot directly (e.g. a shaded header).
  • Printing: when a long table spans several printed pages, browsers can repeat the <thead> (and <tfoot>) on each page.

The order in the source is <caption>, then <colgroup>s, then <thead>, then <tbody>s, then <tfoot>. The footer always appears at the bottom.

The Hidden <tbody>

Here's a classic interview fact. If you write <tr> elements directly inside <table> (like our first example), the HTML parser automatically inserts a <tbody> around them. Open the browser's DevTools (Elements panel) on our first example and you'll see a <tbody> you never typed. This matters when you write CSS selectors such as table > tr, which will match nothing — the rows are actually children of tbody.

Because of this, it's good practice to always write <tbody> yourself, as the rest of the examples in this chapter do. Validators such as html-validate even have a rule (prefer-tbody) that reminds you to do it.


Merging Cells: colspan and rowspan

  • colspan="n" makes a cell stretch across n columns (to the right).
  • rowspan="n" makes a cell stretch down across n rows.

colspan

<table>
  <tbody>
    <tr>
      <th scope="col">Day</th>
      <th scope="col">9–10</th>
      <th scope="col">10–11</th>
    </tr>
    <tr>
      <th scope="row">Mon</th>
      <td colspan="2">DBMS Lab</td>
    </tr>
  </tbody>
</table>

The Monday row has only two cells in the code, but “DBMS Lab” occupies two column slots, so the row still adds up to 3 columns.

rowspan

<table>
  <tbody>
    <tr>
      <th scope="row">Mon</th>
      <td>DS</td>
      <td rowspan="2">Break</td>
    </tr>
    <tr>
      <th scope="row">Tue</th>
      <td>OS</td>
    </tr>
  </tbody>
</table>

“Break” starts in the Monday row and extends down into the Tuesday row. So in the Tuesday row we leave out the cell that “Break” already covers — Tuesday has only two cells in the code.

Worked Example: A Timetable With Both

The golden rule: every row must fill the same number of column slots, counting slots taken by spans from earlier rows. Let's plan a 5-column timetable on paper first:

            col 1   col 2        col 3        col 4          col 5
          ┌───────┬────────────┬────────────┬──────────────┬─────────────┐
header    │ Day   │ 9:00–10:00 │ 10:00–11:00│ 11:00–11:30  │ 11:30–12:30 │
          ├───────┼────────────┼────────────┼──────────────┼─────────────┤
Mon       │ Mon   │ DS         │ OS         │              │ Maths       │
          ├───────┼────────────┼────────────┤              ├─────────────┤
Tue       │ Tue   │ Maths      │ DS         │    Break     │ OS          │
          ├───────┼────────────┴────────────┤ (rowspan=3)  ├─────────────┤
Wed       │ Wed   │ DBMS Lab (colspan=2)    │              │ DS          │
          └───────┴─────────────────────────┴──────────────┴─────────────┘

Now count the cells we must write in each row:

RowCells writtenSlots used
HeaderDay, 9:00, 10:00, 11:00, 11:305
MonMon, DS, OS, Break (rowspan=3), Maths1 + 1 + 1 + 1 + 1 = 5
TueTue, Maths, DS, OS4 + 1 (Break from above) = 5
WedWed, DBMS Lab (colspan=2), DS1 + 2 + 1 (Break from above) + 1 = 5

Every row adds up to 5, so the table is consistent. Here's the full page, with a little CSS to make the grid visible:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Timetable</title>
  <style>
    table { border-collapse: collapse; }
    th, td { border: 1px solid #555; padding: 6px 10px; text-align: center; }
    thead th { background: #e8eefc; }
  </style>
</head>
<body>
  <table>
    <caption>Timetable – CSE Semester 3</caption>
    <thead>
      <tr>
        <th scope="col">Day</th>
        <th scope="col">9:00–10:00</th>
        <th scope="col">10:00–11:00</th>
        <th scope="col">11:00–11:30</th>
        <th scope="col">11:30–12:30</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th scope="row">Mon</th>
        <td>DS</td>
        <td>OS</td>
        <td rowspan="3">Break</td>
        <td>Maths</td>
      </tr>
      <tr>
        <th scope="row">Tue</th>
        <td>Maths</td>
        <td>DS</td>
        <td>OS</td>
      </tr>
      <tr>
        <th scope="row">Wed</th>
        <td colspan="2">DBMS Lab</td>
        <td>DS</td>
      </tr>
    </tbody>
  </table>
</body>
</html>

In Chrome you see a bordered grid with the caption centred above it and a light-blue header row. “Break” is a single tall cell running down the fourth column through all three days, and “DBMS Lab” is a single wide cell covering both morning slots on Wednesday.

If the counts don't match, the browser doesn't show an error — it just pushes cells into the wrong columns or leaves a ragged edge. That's why planning on paper first saves time.


Column Groups: <colgroup> and <col>

Since tables are built row by row, how do you style a whole column — say, highlight the “Marks” column? You can describe columns with <colgroup> and <col>, placed right after the caption:

<table>
  <caption>Results</caption>
  <colgroup>
    <col>
    <col span="2" class="marks">
  </colgroup>
  <tbody>
    <tr>
      <th scope="col">Student</th>
      <th scope="col">Mid-sem</th>
      <th scope="col">End-sem</th>
    </tr>
    <tr>
      <td>Aisha</td>
      <td>42</td>
      <td>78</td>
    </tr>
  </tbody>
</table>
col.marks { background-color: #fff6d6; }

The first <col> describes column 1; the second, with span="2", describes columns 2 and 3. Be aware that only a few CSS properties work on columns: background, border (only when the table uses border-collapse: collapse), width and visibility. Properties like color or text-align won't apply through <col>.


Styling Tables with CSS

Old HTML styled tables with attributes. All of these are obsolete in the HTML Living Standard:

Obsolete attributeCSS replacement
border="1" on <table>border: 1px solid on th, td
cellpaddingpadding on th, td
cellspacingborder-spacing (or border-collapse: collapse)
width, heightwidth, height
align, valigntext-align, vertical-align
bgcolorbackground-color
summaryA <caption> or a paragraph before the table

The most important CSS property for tables is border-collapse:

border-collapse: separate (default)      border-collapse: collapse
┌────┐┌────┐                             ┌────┬────┐
│ A  ││ B  │   each cell has its         │ A  │ B  │   neighbouring borders
└────┘└────┘   own border, with gaps     ├────┼────┤   merge into one line
┌────┐┌────┐                             │ C  │ D  │
│ C  ││ D  │                             └────┴────┘
└────┘└────┘

A common “zebra stripes” style for readability:

table { border-collapse: collapse; }
th, td { border: 1px solid #ccc; padding: 8px; }
tbody tr:nth-child(even) { background-color: #f4f4f4; }

Wide Tables on Phones

A table with many columns can be wider than a phone screen and make the whole page scroll sideways. A simple fix is to wrap the table in a container that scrolls on its own:

<div class="table-wrap">
  <table>
    <tbody>
      <tr><th scope="col">Col 1</th><th scope="col">Col 2</th></tr>
      <tr><td>Data</td><td>Data</td></tr>
    </tbody>
  </table>
</div>
.table-wrap { overflow-x: auto; }

We'll meet <div> properly in Block vs Inline Elements: div & span.


Don't Use Tables for Layout

In the early 2000s, whole websites were laid out with giant invisible tables — a sidebar in one cell, content in another. Don't do this.

  • Screen readers announce “table, 3 columns, 5 rows” and read the page cell by cell, which is confusing when it isn't data.
  • Layout tables can't easily adapt to small screens.
  • Content and presentation get tangled together, making the page hard to change.

Use tables only for tabular data. For page layout, use CSS Flexbox and Grid.


Common Mistakes

  • Rows with different numbers of slots after using colspan/rowspan — always count.
  • Writing a cell where a rowspan from above already sits, which pushes the rest of the row one column to the right.
  • Using <td> with bold text instead of <th> for headers.
  • Putting <caption> anywhere but first inside <table>.
  • Putting text or <div>s directly inside <table> or <tr>. Only cells go inside rows; content goes inside cells.
  • Using border="1" and cellpadding from old tutorials — use CSS.
  • Using tables to position things on a page.

Interview and Exam Questions

1. What is the difference between <th> and <td>?

<th> is a header cell that labels other cells (bold and centred by default); <td> is a data cell. Screen readers use <th> cells to announce the context of each data cell.

2. What do colspan and rowspan do?

colspan makes a cell span several columns horizontally; rowspan makes a cell span several rows vertically. When a cell spans into later rows, those rows must omit the covered cells.

3. A table has 4 columns. Row 1 contains a cell with rowspan="2" in the first column. How many cells should row 2 contain?

3. The first column of row 2 is already occupied by the spanning cell from row 1, so only 3 cells are written: 3 + 1 = 4 slots.

4. Why might table > tr in CSS not select any rows?

Because the HTML parser automatically wraps rows that are direct children of <table> in an implicit <tbody>. The rows are then children of tbody, not of table. Use table tr or tbody > tr.

5. What are <thead>, <tbody> and <tfoot> used for?

They group rows into header, body and footer sections. This adds meaning for assistive technologies, makes styling easier, and lets browsers repeat headers/footers on each printed page.

6. What is the scope attribute?

An attribute on <th> that states whether the header applies to a column (col), a row (row), a column group (colgroup) or a row group (rowgroup). It helps screen readers associate data cells with their headers.

7. Why shouldn't tables be used for page layout?

They give non-tabular content table semantics (confusing for screen readers), don't adapt well to different screen sizes, and mix presentation into HTML. CSS Flexbox and Grid are the correct tools.

8. How do you add borders to a table in modern HTML?

With CSS: table { border-collapse: collapse; } th, td { border: 1px solid #000; }. The border attribute on <table> is obsolete.


Summary

  • Tables are for tabular data only, built row by row: <table> → <tr> → <th>/<td>.
  • Use <th> with scope for headers, and <caption> (first child) for a title.
  • Group rows with <thead>, <tbody> and <tfoot>; the parser adds an implicit <tbody> if you don't.
  • colspan merges cells across columns, rowspan down rows; every row must fill the same number of slots.
  • <colgroup>/<col> describe columns, but only a few CSS properties apply to them.
  • Style tables with CSS (border-collapse, border, padding); attributes like border, cellpadding and bgcolor are obsolete.
  • Never use tables for page layout.

So far we have only shown information. In the next chapter, Forms, we'll start collecting information from users.