๐ Chapter: Using Tables in HTML
Tables in HTML are used to organize data into rows and columns, much like how you see data in spreadsheets. Whether you’re showing a timetable, a list of prices, or any tabular data, the <table>
element is your go-to.
๐ท๏ธ Basic Structure of a Table
A table is created using the <table>
tag. The content is then divided into:
- Rows: defined using the
<tr>
tag (short for “table row”) - Cells: inside each row, data is placed using the
<td>
tag (short for “table data”)
๐ Example:
<table border="1">
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
</tr>
<tr>
<td>Row 2, Cell 1</td>
<td>Row 2, Cell 2</td>
</tr>
</table>
This creates a 2ร2 table with two rows and two columns. The border="1"
attribute adds a border around the table cells.
๐ Adding Table Headings
To define column headers, use the <th>
tag instead of <td>
. Headings are usually bold and centered by default.
๐ Example with Headings:
<table border="1">
<tr>
<th>Subject</th>
<th>Marks</th>
</tr>
<tr>
<td>Math</td>
<td>95</td>
</tr>
<tr>
<td>Science</td>
<td>90</td>
</tr>
</table>
This renders:
Subject | Marks |
---|---|
Math | 95 |
Science | 90 |
๐ Merging Cells โ colspan
and rowspan
Sometimes you need to merge cells across rows or columns.
๐น colspan
โ Merge columns:
<table border="1">
<tr>
<th colspan="2">Student Info</th>
</tr>
<tr>
<td>Name</td>
<td>John</td>
</tr>
</table>
๐น rowspan
โ Merge rows:
<table border="1">
<tr>
<td rowspan="2">Class 10</td>
<td>English</td>
</tr>
<tr>
<td>Math</td>
</tr>
</table>
๐งฑ Table Tags Overview
Tag | Description |
<table> |
Defines the table |
<tr> |
Defines a row in the table |
<td> |
Defines a cell with data |
<th> |
Defines a table header cell |
colspan |
Merges cells horizontally |
rowspan |
Merges cells vertically |
๐ Complete Example โ Student Table
<!DOCTYPE html>
<html>
<head>
<title>HTML Table Example</title>
</head>
<body>
<h2>Student Marks Table</h2>
<table border="1">
<tr>
<th>Roll No</th>
<th>Name</th>
<th>Subject</th>
<th>Marks</th>
</tr>
<tr>
<td>1</td>
<td>Amit</td>
<td>English</td>
<td>85</td>
</tr>
<tr>
<td>2</td>
<td>Reena</td>
<td>Math</td>
<td>95</td>
</tr>
<tr>
<td>3</td>
<td>Sameer</td>
<td>Science</td>
<td>88</td>
</tr>
</table>
</body>
</html>
โ Tips
- Tables can also contain images, links, and even forms inside
<td>
cells. - Always use
<th>
for headings to improve accessibility and clarity. - For better structure, avoid skipping
<tr>
or<td>
in between.
๐งพ Conclusion
Tables are powerful tools in HTML for displaying data clearly in a tabular format. Whether it’s for a pricing sheet, student list, or schedules, mastering the basic tags like <table>
, <tr>
, <td>
, and <th>
is essential.