MSDN Documentation

Reference Guide

Working with HTML Tables

HTML tables are used to display data in rows and columns. They are structured using elements like <table>, <thead>, <tbody>, <tr> (table row), <th> (table header), and <td> (table data).

Table Structure

A basic table consists of a containing <table> element. Within the table, rows are defined using <tr>. The first row typically contains headers defined by <th> elements, and subsequent rows contain data cells defined by <td> elements.

Example of a Simple Table

<table>
<thead>
<tr>
<th>Product Name</th>
<th>Price</th>
<th>Availability</th>
</tr>
</thead>
<tbody>
<tr>
<td>SuperWidget</td>
<td>$19.99</td>
<td>In Stock</td>
</tr>
<tr>
<td>MegaGizmo</td>
<td>$29.50</td>
<td>Out of Stock</td>
</tr>
</tbody>
</table>

Table Caption

The <caption> element provides a title or brief description for the table. It should be the first child element of the <table> element.

Example with Caption

<table>
<caption>Monthly Sales Report</caption>
<thead>
<tr>
<th>Month</th>
<th>Sales ($)</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>15000</td>
</tr>
<tr>
<td>February</td>
<td>18000</td>
</tr>
</tbody>
</table>

Column and Row Spanning

You can make cells span multiple columns or rows using the colspan and rowspan attributes, respectively.

Example with Colspan and Rowspan

<table>
<caption>Project Timeline</caption>
<thead>
<tr>
<th rowspan="2">Task</th>
<th colspan="2">Phase 1</th>
<th colspan="2">Phase 2</th>
</tr>
<tr>
<th>Start Date</th>
<th>End Date</th>
<th>Start Date</th>
<th>End Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>Design</td>
<td>2023-01-15</td>
<td>2023-02-10</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Development</td>
<td></td>
<td></td>
<td>2023-02-11</td>
<td>2023-04-30</td>
</tr>
</tbody>
</table>

Styling Tables

CSS can be used extensively to style tables for better readability and appearance. Common styling properties include border, padding, background-color, and text alignment.

Accessibility Considerations

Ensure your tables are accessible. Use semantic HTML elements like <th> and <caption>. For complex tables, consider using the scope attribute on <th> elements to associate headers with their data cells.