Table Tag
The HTML table tag has done wonders for the internet as a whole. However, tables are often used as grids or containers, which is not the appropriate use of HTML tables. Tables are not very flexible and are primarily intended to show tabular data. The tags of a table require more opening and closing tags than the average HTML element. Let's look at an example to see:
Example
<table>
<tr>
<td>Row 1 Column 1</td>
<td>Row 1 Column 2</td>
</tr>
<tr>
<td>Row 2 Column 1</td>
<td>Row 2 Column 2</td>
</tr>
</table>
Result
Row 1 Column 1 | Row 1 Column 2 |
Row 2 Column 1 | Row 2 Column 2 |
Three separate tags are involved in creating an HTML table, <table>
, <tr>
, and <td>
. The <table>
is simply the encasing of a table. To identify a new row, which must come first, you should use the <tr>
tag. Inside of the table row tag, you can specify columns by using the <td>
tag.
It's worth mentioning that you must structure the table and table tags properly. All <tr>
must be opened and closed inside the <table>
tags. The <th>
and <td>
tags must be opened and closed inside the <tr>
tags.
Table Headers
Sometimes when creating an HTML table, you might want the top row to stand out from the rest as a heading. All you need to do is replace the HTML table column tag, <td>
, with a table header tag, <th>
. It is entirely possible to use these multiple times in different rows to have multiple "sections" in your table.
Example
<table>
<tr>
<th>Row 1 Column 1</th>
<th>Row 1 Column 2</th>
</tr>
<tr>
<td>Row 2 Column 1</td>
<td>Row 2 Column 2</td>
</tr>
</table>
Merging Columns
Sometimes, you might want to merge two columns to display your data correctly in a row. All we need to do is use the colspan
attribute of the HTML table. Let's merge two columns in one row.
Example
<table>
<tr>
<td colspan="2">Row 1 Column 1</td>
</tr>
<tr>
<td>Row 2 Column 1</td>
<td>Row 2 Column 2</td>
</tr>
</table>
Result
Row 1 Column 1 | |
Row 2 Column 1 | Row 2 Column 2 |