Creating Tables in HTML
Tables are used to display data in a structured format of rows and columns. HTML provides several tags to build tables and format them as needed.
Basic Table Structure
Here's a simple table with 3 rows and 2 columns:
<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Alice</td>
<td>24</td>
</tr>
<tr>
<td>Bob</td>
<td>30</td>
</tr>
</table>
Table Elements
<table>
: Defines the table container.<tr>
: Defines a row in the table.<th>
: Defines a table header cell (bold and centered by default).<td>
: Defines a standard table data cell.border
: Attribute to set table border (better done with CSS).
Table with Caption
You can add a caption to describe the table:
<table border="1">
<caption>Employee List</caption>
<tr>
<th>Name</th>
<th>Department</th>
</tr>
<tr>
<td>John</td>
<td>HR</td>
</tr>
</table>
Merging Cells
You can merge rows or columns using rowspan
and colspan
:
<table border="1">
<tr>
<th colspan="2">Employee</th>
</tr>
<tr>
<td>Name</td>
<td>Jane</td>
</tr>
</table>
Styling with CSS
Use CSS for better control and appearance:
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ccc;
padding: 8px;
text-align: left;
}
th {
background-color: #f5f5f5;
}
Accessibility Tips
- Use
<caption>
to describe the purpose of the table. - Use
<th>
for headers and scope attributes if needed. - Keep table structure simple for screen readers.