Tables
Tables are used to display data in rows and columns, like in spreadsheets or databases. In HTML, tables help organize content in a grid format.
Main
Table Tags:
- <table>:
Defines the entire table.
- <tr>:
Defines a table row.
- <td>:
Defines a table cell (table data) inside a row.
Basic
Table Structure:
<table>
<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 2x2 table with 2 rows
and 2 columns.
Adding
Table Headers (<th>)
Headers are used for column or row
titles. They appear bold and centered by default.
<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Alice</td>
<td>25</td>
</tr>
<tr>
<td>Bob</td>
<td>30</td>
</tr>
</table>
Example:
Create a Table File for Testing
- Create a file named table-example.html in your htdocs (XAMPP) or www (WAMP) folder.
- Paste this code:
<!DOCTYPE
html>
<html>
<head>
<title>HTML Table Example</title>
</head>
<body>
<h2>Student Scores</h2>
<table border="1" cellpadding="5"
cellspacing="0">
<tr>
<th>Student Name</th>
<th>Subject</th>
<th>Score</th>
</tr>
<tr>
<td>Saqib Jahangir</td>
<td>Math</td>
<td>90</td>
</tr>
<tr>
<td>Ali Khan</td>
<td>Science</td>
<td>85</td>
</tr>
<tr>
<td>Aisha</td>
<td>English</td>
<td>88</td>
</tr>
</table>
</body>
</html>
- Open your browser and go to:
http://localhost/table-example.html
You will see a simple table with
student names, subjects, and scores.
Attributes
used:
- border="1":
Adds a border to the table cells.
- cellpadding="5":
Adds space inside each cell.
- cellspacing="0":
Removes space between cells.
Summary:
- Use <table> to start the table.
- Inside <table>, use <tr> to create rows.
- Inside each <tr>, use <td> for regular cells or <th> for header cells.
- Tables organize data clearly in rows and columns.