HTML Tables
Learn how to create and format tables in HTML
Introduction to HTML Tables
HTML tables are used to display tabular data in rows and columns.
Tables in HTML are used to organize data into rows and columns — like in Excel.
Basic Table Elements:
</table>-Creates the table<tr>- Table row<th>- Table heading (bold & centered)<td>- Table data (regular cell)
Basic Tables Structure
<table>
<tr>
<th>Heading 1</th>
<th>Heading 2</th>
</tr>
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
</tr>
</table>
Add Borders
To add borders to your table, you can use CSS. Here's an example:
<table>
<tr>
<table border="1">
...
</table>
Better with CSS:
Or you can use CSS styles:
table {
width: 100%;
border-collapse: collapse;
margin-top: 30px;
}
th, td {
border: 1px solid #ccc;
padding: 10px;
text-align: left;
}
th {
background-color: #f0f0f0;
}
Output
| Heading 1 | Heading 2 |
|---|---|
| Row 1, Cell 1 | Row 1, Cell 2 |
Multiple Rows and Columns Example
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
<tr>
<td>Alice</td>
<td>25</td>
<td>India</td>
</tr>
<tr>
<td>Bob</td>
<td>30</td>
<td>USA</td>
</tr>
</table>
Output
| Name | Age | Country |
|---|---|---|
| Alice | 25 | India |
| Bob | 30 | USA |
Table Attributes
Tables can have various attributes to control their appearance:
| Attribute | Description |
|---|---|
| border | Thickness of border |
| cellspacing | Space between cells |
| cellpadding | Space inside cell border |
| width / height | Size of table/cell |
| align | Align table (deprecated, use CSS) |
Using colspan and rowspan
colspan-One cell spans multiple columnsrowspan- One cell spans multiple rows
<table border="1">
<tr>
<th rowspan="2">Name</th>
<th colspan="2">Marks</th>
</tr>
<tr>
<td>Math</td>
<td>Science</td>
</tr>
<tr>
<td>John</td>
<td>90</td>
<td>95</td>
</tr>
</table>
Output
| Name | Marks | |
|---|---|---|
| Math | Science | |
| John | 90 | 95 |
Conclusion
HTML tables are essential for displaying structured data. They can be styled with CSS to enhance their appearance and usability. Remember to use tables for tabular data only, not for layout purposes.
Practice creating tables with different attributes and styles to become comfortable with HTML tables.
Semantic Table Tags
Use these for better accessibility and structure:
| Tag | Purpose |
|---|---|
| <thead> | Group header rows |
| <tbody> | Group body rows |
| <tfoot> | Group footer rows |
Examples
<table border="1">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Pen</td>
<td>$1</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total</td>
<td>$1</td>
</tr>
</tfoot>
</table>
Output
| Product | Price |
|---|---|
| Pen | $1 |
| Total | $1 |
Using semantic tags like <thead>, <tbody>, and <tfoot>
helps screen readers and search engines understand the structure of your table better.