HTML Tables – Complete Guide from Basic to Advanced
1. HTML Table Basics
An HTML table is created using the <table> tag. Rows are defined using <tr>, and columns (cells) are created using <td> (data cells) or <th> (header cells).
Example:
<table>
<tr>
<th> Name </th>
<th> Age </th>
</tr>
<tr>
<td> John </td>
<td> 25 </td>
</tr>
</table>
Output:
Name Age
John 25
2. Table Borders
By default, tables do not have borders. Use the border attribute or CSS to add a border.
Example:
<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>John</td>
<td>25</td>
</tr>
</table>
CSS Method (Recommended)
<style>
table, th, td {
border: 1px solid black;
}
</style>
3. Table Sizes
The size of a table can be controlled using width and height.
Example:
<table style="width: 50%; height: 100px;">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</table>
4. Table Headers
The <th> tag is used for table headers. It makes text bold and center-aligned by default.
Example:
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
</tr>
<tr>
<td>Apple</td>
<td>$1</td>
</tr>
</table>
5. Padding & Spacing
padding: Space inside a cell.
border-spacing: Space between cells.
Example:
<style>
table {
border-collapse: separate;
border-spacing: 10px;
}
th, td {
padding: 10px;
}
</style>
6. Colspan & Rowspan.
colspan: Merges multiple columns.
rowspan: Merges multiple rows.
Example (Colspan):
<table border="1">
<tr>
<th colspan="2">Full Name</th>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
</tr>
</table>
Example (Rowspan):
<table border="1">
<tr>
<td rowspan="2">John</td>
<td>25</td>
</tr>
<tr>
<td>Male</td>
</tr>
</table>.
7. Table Styling
Use CSS to style tables.
Example:
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
</style>
8. Table Colgroup
The <colgroup> tag styles specific columns.
Example:
<table border="1">
<colgroup>
<col span="1" style="background-color:yellow">
</colgroup>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>John</td>
<td>25</td>
</tr>
</table>
Top comments (0)