HTML tables are used to organize data into rows and columns. They are created using the <table>
element and provide a structured way to display data such as pricing plans, schedules, or comparisons.
HTML tables consist of multiple elements, including:
<table>
: Defines the table.<tr>
: Defines a table row.<td>
: Defines a table cell (data).<th>
: Defines a header cell.To create a simple table, use the following basic structure:
<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
<tr>
<td>John</td>
<td>25</td>
<td>New York</td>
</tr>
<tr>
<td>Alice</td>
<td>30</td>
<td>London</td>
</tr>
</table>
Output:
Name | Age | City |
---|---|---|
John | 25 | New York |
Alice | 30 | London |
Each table cell is defined by a <td>
and a </td>
tag.
td
stands for table data.
Everything between <td>
and </td>
are the content of the table cell.
Each table row starts with a <tr>
and ends with a </tr>
tag.
tr
stands for table row.
Sometimes you want your cells to be table header cells. In those cases use the <th>
tag instead of the <td>
tag:
th
stands for table header.
HTML tables support advanced features like rowspan
and colspan
to merge cells, and attributes for enhanced styling and accessibility.
rowspan
and colspan
Use rowspan
to span rows and colspan
to span columns.
<table border="1">
<tr>
<th>Item</th>
<th>Details</th>
</tr>
<tr>
<td rowspan="2">Laptop</td>
<td>Brand: Dell</td>
</tr>
<tr>
<td>Price: $1000</td>
</tr>
<tr>
<td colspan="2">Total Items: 5</td>
</tr>
</table>
Output:
Item | Details |
---|---|
Laptop | Brand: Dell |
Price: $1000 | |
Total Items: 5 |
CSS can be used to style HTML tables for better appearance and usability. Example:
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 10px;
border: 1px solid #ddd;
text-align: left;
}
th {
background-color: #f4f4f4;
}
</style>
<table>
: Defines the table.<tr>
: Defines a table row.<td>
: Defines a table data cell.<th>
: Defines a table header cell.<caption>
: Adds a caption to the table.
The <table>
tag is the container for all other table elements. It defines the table structure and includes rows, columns, and other elements.
<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>John</td>
<td>25</td>
</tr>
</table>
Output:
Name | Age |
---|---|
John | 25 |
border
attribute adds a border to the table.
Advanced examples like spanning rows and columns can be achieved with rowspan
and colspan
.
<table border="1">
<tr>
<th>Item</th>
<th>Details</th>
</tr>
<tr>
<td rowspan="2">Laptop</td>
<td>Brand: Dell</td>
</tr>
<tr>
<td>Price: $1000</td>
</tr>
</table>
<caption>
and <th>
elements.<th>
tag?
The <th>
tag defines header cells in a table, which are bold and centered by default. It helps in distinguishing headers from regular data cells.
Use CSS media queries and properties like overflow-x
to make tables responsive. Example:
table {
display: block;
overflow-x: auto;
}