HTML tables are used to display structured data in rows and columns.
They are commonly used for data representation, pricing tables, schedules, and reports.
What This Tutorial Covers:
- Basic HTML table structure
- Adding table headers
- Merging cells (colspan and rowspan)
- Adding borders and styling with CSS
- Responsive tables
- Best practices for using tables
1. Basic HTML Table Structure
A table is created using the <table> element, with rows (<tr>) and columns (<td> for table data).
Example:
<table>
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>
Explanation:
- <table> creates the table.
- <tr> (table row) defines a row.
- <td> (table data) defines a cell inside a row.
2. Adding Table Headers
Use <th> instead of <td> to create bold, centered headers.
Example:
<table>
<tr>
<th>Product</th>
<th>Price</th>
</tr>
<tr>
<td>Phone</td>
<td>$500</td>
</tr>
<tr>
<td>Laptop</td>
<td>$1000</td>
</tr>
</table>
Explanation:
- <th> (table header) bolds and centers text by default.
3. Merging Cells with colspan and rowspan
3.1 Merge Columns (colspan)
Use colspan to make a cell span multiple columns.
<table>
<tr>
<th colspan="2">Product Details</th>
</tr>
<tr>
<td>Phone</td>
<td>$500</td>
</tr>
</table>
3.2 Merge Rows (rowspan)
Use rowspan to make a cell span multiple rows.
<table>
<tr>
<th rowspan="2">Category</th>
<td>Electronics</td>
</tr>
<tr>
<td>Clothing</td>
</tr>
</table>
4. Adding Borders and Styling with CSS
Example:
<style>
table {
width: 50%;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: left;
}
th {
background-color: lightgray;
}
</style>
<table>
<tr>
<th>Product</th>
<th>Price</th>
</tr>
<tr>
<td>Tablet</td>
<td>$300</td>
</tr>
</table>
Explanation:
- border-collapse: collapse; removes spacing between borders.
- padding: 8px; adds space inside cells.
- background-color: lightgray; gives headers a background color.
5. Responsive Tables
For large tables, use CSS overflow to make them scrollable.
Example:
<style>
.table-container {
overflow-x: auto;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 8px;
}
</style>
<div class="table-container">
<table>
<tr>
<th>Item</th>
<th>Price</th>
<th>Stock</th>
<th>Category</th>
</tr>
<tr>
<td>Phone</td>
<td>$500</td>
<td>20</td>
<td>Electronics</td>
</tr>
</table>
</div>
Explanation:
- .table-container adds horizontal scrolling for small screens.
6. Best Practices for Using Tables
Use <th> for Headings
- Helps with readability and accessibility.
Keep Tables Simple
- Avoid unnecessary nested tables.
Use border-collapse
- Ensures clean table design.
Make Tables Responsive
- Use CSS scrolling or flexible widths.