To create a table in HTML, you use a set of tags that define the table’s structure: <table>
, <tr>
, <th>
, and <td>
.
Basic Structure of an HTML Table
- <table>: Starts and ends the table.
- <tr>: Table row; contains header or data cells.
- <th>: Table header cell; bold and centered by default.
- <td>: Table data cell; holds table content.
Example: Simple Table
<table> <tr> <th>Name</th> <th>Age</th> <th>Country</th> </tr> <tr> <td>Alice</td> <td>30</td> <td>USA</td> </tr> <tr> <td>Bob</td> <td>25</td> <td>Canada</td> </tr> </table>
- The first row, wrapped in
<tr>
, contains three<th>
header cells. - The next two rows each contain three
<td>
cells with data.
Adding More Functionality
Table Section Elements:
- <thead>: For header rows; placed at the top.
- <tbody>: For main table body rows.
- <tfoot>: For footer rows.
Example with Sections:
<table> <thead> <tr> <th>Product</th> <th>Price</th> </tr> </thead> <tbody> <tr> <td>Notebook</td> <td>$5</td> </tr> <tr> <td>Pen</td> <td>$1</td> </tr> </tbody> <tfoot> <tr> <td>Total</td> <td>$6</td> </tr> </tfoot> </table>
Colspan and Rowspan allow you to merge cells across columns or rows, using the colspan
or rowspan
attributes.
Summary Table of Key Elements
Tag | Purpose | Example |
---|---|---|
<table> | Table container | <table>...</table> |
<tr> | Table row | <tr>...</tr> |
<th> | Table header (bold/centered) | <th>Heading</th> |
<td> | Table data (content) | <td>Value</td> |
You can add as many rows (<tr>
) and columns (<td>
/<th>
) as needed.
Tip: To control the appearance of your table (like border, color, spacing), use CSS for styling rather than inline HTML attributes.