Basic Table Structure:
A basic HTML table consists of the following elements:
<table>
: The container element for the entire table.<tr>:
Defines a row within the table.<th>:
Defines a header cell within a row.<td>:
Defines a standard cell within a row.
Example:
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
</table>
Table Headers and Data:
In HTML tables, the <th> element is used to define header cells, while the <td> element is used to define standard data cells.
Example:
<tr>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
<tr>
<td>John</td>
<td>30</td>
<td>USA</td>
</tr>
<tr>
<td>Alice</td>
<td>25</td>
<td>UK</td>
</tr>
</table>
Table Captions:
You can add a caption to a table using the <caption> element. Captions provide a brief description or title for the table.
Example:
<caption>Employee Information</caption>
<tr>
<th>Name</th>
<th>Age</th>
<th>Department</th>
</tr>
<tr>
<td>John</td>
<td>30</td>
<td>IT</td>
</tr>
<tr>
<td>Alice</td>
<td>25</td>
<td>Marketing</td>
</tr>
</table>
Table Borders and Styling:
You can use CSS to style tables, including adding borders, changing cell colors, and adjusting text alignment.
Example:
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
</style>
Spanning Rows and Columns:
You can merge multiple cells to span rows or columns using the colspan and rowspan attributes.
Example:
<tr>
<th>Name</th>
<th colspan="2">Details</th>
</tr>
<tr>
<td>John</td>
<td>30</td>
<td>USA</td>
</tr>
</table>
Accessibility Considerations:
When creating tables, ensure they are accessible to all users, including those using screen readers. Use appropriate markup, provide meaningful captions and headers, and use ARIA attributes if necessary.
Practice Excercise Practice now