What are HTML Tables?
HTML tables allow you to organize data into rows and columns, making it easy to display information in a structured way. They are perfect for displaying data like schedules, lists, and comparison charts.
Basic Structure of an HTML Table
An HTML table is defined with the <table>
tag. Inside the table, you can use <tr>
for table rows, <th>
for table headers, and <td>
for table data cells.
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>
Components of an HTML Table
- Table: The container for all table-related tags.
<table>...</table>
- Table Row: Defines a row in a table.
<tr>...</tr>
- Table Header: Defines a header cell in a table (bold and centred by default).
<th>Header</th>
- Table Data: Defines a standard cell in a table.
<td>Data</td>
Example of a Simple Table
<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>John</td>
<td>30</td>
</tr>
<tr>
<td>Jane</td>
<td>25</td>
</tr>
</table>
This example creates a table with a border, two columns (Name and Age), and two rows of data (John, 30 and Jane, 25).
Adding Styles to Tables
You can enhance the appearance of your tables using CSS. Below is an example:
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 12px;
border: 1px solid #ddd;
text-align: left;
}
th {
background-color: #f2f2f2;
}
</style>
<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>John</td>
<td>30</td>
</tr>
<tr>
<td>Jane</td>
<td>25</td>
</tr>
</table>
In this example, the table stretches to 100% of the container’s width, and cells have padding, borders, and background colour.
Merging Cells
You can merge cells in a table using colspan
for columns and rowspan
for rows.
Column Span Example
<table border="1">
<tr>
<th colspan="2">Header</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>
In this example, the header spans two columns.
Row Span Example
<table border="1">
<tr>
<th rowspan="2">Header</th>
<td>Data 1</td>
</tr>
<tr>
<td>Data 2</td>
</tr>
</table>
In this example, the header spans two rows.
HTML tables are a powerful way to display structured data on a webpage. Understanding how to create and style tables can greatly enhance the readability and presentation of your data.