HTML tables allow web developers to arrange data into rows and columns.
Example:
HTML
<!DOCTYPE html>
<html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<h2>HTML Table</h2>
<table>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
</table>
</body>
</html>
A table in HTML consists of table cells inside rows and columns.
Example:
HTML
<!DOCTYPE html>
<html>
<body>
<h2>A basic HTML table</h2>
<TABLE cellSpacing=0 cellPadding=0 width="100%" border=1>
<TBODY>
<TR>
<TD> Name</TD>
<TD> Address</TD></TR>
<TR>
<TD> Itupto</TD>
<TD> Sri Lanka</TD></TR></TBODY></TABLE>
<p>To understand the example better, we have added borders to the table.</p>
</body>
</html>
Each table cell is defined by a <td>
and a </td>
tag.
td
stands for table data.
<table>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
</table>
Example:
HTML
<!DOCTYPE html>
<html>
<style>
table, th, td {
border:1px solid black;
}
</style>
<body>
<h2>TD elements define table cells</h2>
<table style="width:100%">
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
</table>
<p>To understand the example better, we have added borders to the table.</p>
</body>
</html>
Each table row starts with a <tr>
and ends with a </tr>
tag.
<table>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>
Example:
HTML
<!DOCTYPE html>
<html>
<style>
table, th, td {
border:1px solid black;
}
</style>
<body>
<h2>TR elements define table rows</h2>
<table style="width:100%">
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>
<p>To understand the example better, we have added borders to the table.</p>
</body>
</html>
Sometimes you want your cells to be table header cells. In those cases use the <th>
tag instead of the <td>
tag:
<table>
<tr>
<th>Person 1</th>
<th>Person 2</th>
<th>Person 3</th>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>
Example:
HTML
<!DOCTYPE html>
<html>
<style>
table, th, td {
border:1px solid black;
}
</style>
<body>
<h2>TH elements define table headers</h2>
<table style="width:100%">
<tr>
<th>Person 1</th>
<th>Person 2</th>
<th>Person 3</th>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>
<p>To understand the example better, we have added borders to the table.</p>
</body>
</html>