HTML Tables

Purpose of Tables

Tables are used to present structured data in rows and columns. Ideal for tabular data like schedules, price charts, and comparisons.

Basic Structure

Here are the essential elements of a table:

  • <table>: Container for the entire table
  • <tr>: Table row
  • <th>: Header cell
  • <td>: Data cell
<table>
  <tr>
    <th>Product</th>
    <th>Price</th>
  </tr>
  <tr>
    <td>Laptop</td>
    <td>$999</td>
  </tr>
</table>

Adding Borders

Use the border attribute or CSS for borders:

<table border="1">...</table>

Example CSS Styling

Use CSS for spacing and appearance. This example applies styles to the <table>, <th>, and <td> elements:

table, th, td {
  border: 1px solid black;       /* Adds a 1px solid black border around the table and each cell */
  border-collapse: collapse;     /* Merges adjacent borders into a single border for a cleaner look */
  padding: 10px;                  /* Adds space between the cell content and its border */
}
  • border: 1px solid black — Defines the thickness (1px), style (solid), and color (black) of the border around the table and all cells.
  • border-collapse: collapse — Removes the double borders between cells by merging them into a single border.
  • padding: 10px — Adds extra space between the content of a table cell and its border, improving readability.

Table Caption

Add a title using <caption> inside the table:

<table>
  <caption>Class Roster</caption>
  ...
</table>

Spanning Rows or Columns

You can merge table cells horizontally or vertically using the colspan and rowspan attributes on a <td> or <th> element.

  • colspan – Merges the cell across multiple columns.
    <td colspan="2">Merged Across 2 Columns</td>
  • rowspan – Merges the cell down across multiple rows.
    <td rowspan="3">Merged Across 3 Rows</td>

Example table with both:

<table border="1">
  <tr>
    <th>Header 1</th>
    <th>Header 2</th>
    <th>Header 3</th>
  </tr>
  <tr>
    <td rowspan="2">Row span</td>
    <td>Cell A</td>
    <td>Cell B</td>
  </tr>
  <tr>
    <td colspan="2">Column span</td>
  </tr>
</table>

When merging cells, ensure the total number of columns in each row remains consistent to avoid layout issues.

Semantic Sections

You can organize tables semantically using:

  • <thead> – Table header group
  • <tbody> – Main content
  • <tfoot> – Footer section
<table>
  <thead>
    <tr><th>Name</th><th>Age</th></tr>
  </thead>
  <tbody>
    <tr><td>Alice</td><td>30</td></tr>
  </tbody>
</table>

Practice Prompt

Create a table with:

  • 3 columns: Name, Age, City
  • 3 rows of data
  • A caption
  • Styled borders and padding using CSS
<table>
  <caption>People Info</caption>
  <tr>
    <th>Name</th><th>Age</th><th>City</th>
  </tr>
  <tr>
    <td>Jane</td><td>28</td><td>Toronto</td>
  </tr>
  <tr>
    <td>Mark</td><td>35</td><td>Vancouver</td>
  </tr>
</table>

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic