🌱BeginnerTables

Basic Tables

Build data tables with <table>, <tr>, <th>, and <td> elements.

Overview

HTML tables display tabular data information that naturally fits into rows and columns, like a spreadsheet. The core elements are: - <table>: the table container - <tr>: table row - <th>: table header cell (bold, centered by default) - <td>: table data cell Tables should only be used for tabular data not for page layout. Using tables for layout is outdated practice that hurts accessibility and responsive design. CSS Grid and Flexbox handle layout. The structure always goes: table β†’ tr β†’ th/td.

Key Points

  • β€’<table> β†’ <tr> β†’ <th>/<td> is the required nesting order
  • β€’<th> is for header cells bold and centered by default, semantically different from data
  • β€’<td> is for data cells
  • β€’Tables are for tabular data, NOT for page layout
  • β€’The scope attribute on <th> (scope="col" or scope="row") aids screen reader navigation
  • β€’Add a <caption> inside <table> to give it an accessible title

Examples

A simple data table with headers

<table>
  <tr>
    <th>Name</th>
    <th>Age</th>
    <th>City</th>
  </tr>
  <tr>
    <td>Alice</td>
    <td>30</td>
    <td>New York</td>
  </tr>
  <tr>
    <td>Bob</td>
    <td>25</td>
    <td>London</td>
  </tr>
</table>

Table with a caption and scope attributes

<table>
  <caption>Employee Directory</caption>
  <tr>
    <th scope="col">Name</th>
    <th scope="col">Department</th>
    <th scope="col">Role</th>
  </tr>
  <tr>
    <td>Jane Smith</td>
    <td>Engineering</td>
    <td>Senior Developer</td>
  </tr>
</table>

scope="col" tells screen readers that this header applies to its column.

Row headers with scope="row"

<table>
  <tr>
    <th scope="row">Monday</th>
    <td>Math</td>
    <td>Science</td>
  </tr>
  <tr>
    <th scope="row">Tuesday</th>
    <td>English</td>
    <td>History</td>
  </tr>
</table>

Common Mistakes

  • Using tables for page layout use CSS Grid/Flexbox instead
  • Forgetting <th> for header cells and using <td> for everything
  • Inconsistent number of cells per row each row should have the same number of cells

Note

If you can describe your data with "rows and columns of related values," it probably belongs in a table. If you're arranging page sections, use CSS.

Exercises

Write HTML to solve each exercise. Use Preview to see it render in a live iframe, then mark as done.

Loading editor…

Completed: 0 / 5 exercises

Knowledge Check

Question 1 of 4

What is the correct nesting order for a table?