HTML Tables
HTML tables allow web developers to arrange data into rows and columns.
Define an HTML Table
A table in HTML consists of table cells inside rows.
<table>defines the table itself.<tr>defines a table row.<td>defines a table data cell.<th>defines a table header cell. By default, the text in<th>elements are bold and centered.
Example: Basic Table
html
<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>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>Table Borders
By default, HTML tables have no borders. To add borders, you can use the CSS border property.
Example: Adding Borders with CSS
html
<table style="width:100%; border: 1px solid black;">
<tr>
<th style="border: 1px solid black;">Firstname</th>
<th style="border: 1px solid black;">Lastname</th>
<th style="border: 1px solid black;">Age</th>
</tr>
<tr>
<td style="border: 1px solid black;">Jill</td>
<td style="border: 1px solid black;">Smith</td>
<td style="border: 1px solid black;">50</td>
</tr>
</table>Spanning Columns and Rows
You can make a cell span multiple columns or rows using the colspan and rowspan attributes.
Example: Colspan
This cell spans two columns:
html
<table>
<tr>
<th colspan="2">Name</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
</table>Example: Rowspan
This cell spans two rows:
html
<table>
<tr>
<th>Name</th>
<td>Jill Smith</td>
</tr>
<tr>
<th rowspan="2">Telephone</th>
<td>555-77854</td>
</tr>
<tr>
<td>555-77855</td>
</tr>
</table>Table Caption
The <caption> tag defines a table caption. The <caption> tag must be inserted immediately after the <table> tag.
Test Yourself with an Exercise
Which HTML tag is used to define a table header?