HTML Course 7.4 Basic tables (table, tr, td, th)

HTML Course 7.4: Basic Tables (table, tr, td, th)

Tables allow you to present structured, grid-like data in rows and columns. In HTML, four core elements work together to build a table:

  • <table>: Container for the entire table.
  • <tr>: Defines a table row.
  • <th>: Defines a header cell (usually bold and centered).
  • <td>: Defines a standard data cell.

1. The <table> Element

This is the wrapper for all table content. Common global attributes apply (like id, class, title). In HTML5 you should separate styling into CSS, but older examples sometimes use the border attribute for quick demos.

2. Table Rows with <tr>

Each <tr> element groups one horizontal row of cells. You can mix <th> and <td> within a row. Attributes:

  • align (left, center, right) – alignment of cell content (deprecated in favor of CSS).
  • valign (top, middle, bottom) – vertical alignment (deprecated).

3. Header Cells with <th>

Use <th> to mark cells as headers. Browsers render them bold and centered by default. Important attributes:

  • scope: Defines the relationship to data cells. Values: col, row, colgroup, rowgroup. Improves accessibility.
  • colspan / rowspan: Merge cells horizontally or vertically.

4. Data Cells with <td>

Standard cell for data in a table. Shares colspan and rowspan with <th>. By default, text aligns left and vertical-align is middle.

5. Cell Merging: colspan & rowspan

  • colspan='n': Cell spans n columns.
  • rowspan='m': Cell spans m rows.

6. Grouping Rows: thead, tbody, tfoot

For larger tables, you can semantically group rows:

  • <thead>: Header group.
  • <tbody>: Body group (default if omitted).
  • <tfoot>: Footer group, useful for summaries.

Example: A Complete Table with Caption, Header, Body, Footer


Quarterly Sales Report
Region Q1 Q2 Q3 Q4
North America 150,000 165,000 170,000 180,000
Europe 120,000 130,000 135,000 145,000
Asia 200,000 210,000 220,000 230,000
Total 470,000 505,000 555,000

7. Accessibility Tips

  • Always include a <caption> to describe table content.
  • Use scope on <th> to link headers to data.
  • For complex tables, consider aria-labelledby or aria-describedby.

8. Best Practices

  • Keep tables semantic: Don’t use tables for layout.
  • Use <thead>, <tbody>, <tfoot> for clarity.
  • Rely on CSS (external or inline) for styling, not deprecated HTML attributes.
  • Test keyboard navigation and screen reader behavior.


Posted

in

by

Tags:

Comments

Leave a Reply