HTML tables are used to display data in a structured, tabular format using rows and columns.
A table is ideal for:
A table consists of the following elements:
Tag Description
<table> Defines the table container
<tr> Table row
<th> Table header (bold and centered by default)
<td> Table data (cell content)
<caption> Optional table title
<table>
<caption>Table Title</caption>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>
Example: Simple Table
<table border="1">
<caption>Student Scores</caption>
<tr>
<th>Name</th>
<th>Math</th>
<th>Science</th>
</tr>
<tr>
<td>Alice</td>
<td>85</td>
<td>90</td>
</tr>
<tr>
<td>Bob</td>
<td>78</td>
<td>88</td>
</tr>
</table>
border="1" adds a simple border.
✅ Modern approach: Use CSS for styling borders instead of the border attribute.
Attribute Description
border Sets the border width
cellpadding Space between cell content and cell border
cellspacing Space between cells
width Width of the table
align Aligns table on the page (left, center, right)
CSS allows more advanced styling:
<style>
table {
width: 60%;
border-collapse: collapse; /* Merge borders */
margin: 20px 0;
}
th, td {
border: 1px solid #333;
padding: 8px 12px;
text-align: center;
}
th {
background-color: #3498db;
color: white;
}
tr:nth-child(even) {
background-color: #f2f2f2; /* Zebra stripes */
}
</style>
colspan & rowspanExample:
<table border="1">
<tr>
<th>Name</th>
<th colspan="2">Scores</th>
</tr>
<tr>
<th></th>
<th>Math</th>
<th>Science</th>
</tr>
<tr>
<td>Alice</td>
<td>85</td>
<td>90</td>
</tr>
</table>
For mobile-friendly tables, wrap them in a scrollable container:
<div style="overflow-x:auto;">
<table>
<!-- table content -->
</table>
</div>
Create a webpage demonstrating:
colspan usage<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML Tables Practice</title>
<style>
table {
width: 70%;
border-collapse: collapse;
margin: 20px 0;
font-family: Arial, sans-serif;
}
th, td {
border: 1px solid #333;
padding: 10px;
text-align: center;
}
th {
background-color: #2c3e50;
color: white;
}
tr:nth-child(even) {
background-color: #ecf0f1;
}
</style>
</head>
<body>
<h1>Student Scores Table</h1>
<table>
<caption>Exam Results</caption>
<tr>
<th>Name</th>
<th colspan="2">Scores</th>
</tr>
<tr>
<th></th>
<th>Math</th>
<th>Science</th>
</tr>
<tr>
<td>Alice</td>
<td>85</td>
<td>90</td>
</tr>
<tr>
<td>Bob</td>
<td>78</td>
<td>88</td>
</tr>
<tr>
<td>Charlie</td>
<td>92</td>
<td>81</td>
</tr>
</table>
</body>
</html>