HTML Tables

Tables are matrix of rows and columns. Tables are defined with the <table> tag. Tables are divided into a number of table rows with the <tr> tag and rows are divided into table data with the <td> tag.

images/articles/html/html-tables.webp

A table row can also be divided into table headings with the <th> tag. By default, all major browsers display table headings as bold and centered.

<table>
<tr>
<th>Name</th>
<th>Department</th>
<th>Age</th>
</tr>
<tr>
<td>Steve</td>
<td>Marketing</td>
<td>50</td>
</tr>
<tr>
<td>Edwin</td>
<td>Finance</td>
<td>43</td>
</tr>
</table>

1. Table Border

The default table does not have any borders around it. If you like to add borders, use border attribute with the table element. For example, to create a table with the border of size 1:

<table border="1">

However, this is a primitive way to add a border to a table. A better way to accomplish this task is by using CSS.

2. Spanning Rows and Columns

Spanning Multiple Columns

TheĀ colspan attribute (on <td> or <th> tags) tells how many columns a cell will take. If you increase the width of a cell, you need to eliminate some other cells in the same row to compensate. For example:

<table>
<tr>
<th>Name</th>
<th colspan="2">Cars</th>
</tr>
<tr>
<td>Bill Gates</td>
<td>BMW</td>
<td>Mercedes</td>
</tr>
</table>

Spanning Multiple Rows

Similarly, theĀ rowspan attribute allows a cell to take up more than one row of a table. If you increase the height of a cell, you need to eliminate some other cells in the next rows to compensate.