HTML Tables
Table Structure
The <table> tag defines a table. A table is made up of rows and columns. Each row is defined by the <tr> tag, and each column is defined by the <td> tag. Header cells are defined by the <th> tag. The <thead> and <tbody> tags can be used to group header and body rows, respectively.
Example Table
| Header 1 | Header 2 |
|---|---|
| Row 1, Column 1 | Row 1, Column 2 |
| Row 2, Column 1 | Row 2, Column 2 |
Table Caption
The <caption> tag is used to add a caption to a table. It should be placed immediately after the <table> tag.
| Header 1 | Header 2 |
|---|---|
| Row 1, Column 1 | Row 1, Column 2 |
As seen above, the caption is displayed at the top of the table. And, it is centered.
Colgroups
The <colgroup> element is used to group columns in a table and apply styles or attributes to them collectively.
Each group of columns is defined using the <col> element within the <colgroup>.
The span attribute of the <col> element specifies the number of columns the <col> element should span. If we don't provide a span attribute, it defaults to 1.
Example
| Header 1 | Header 2 | Header 3 | Header 4 |
|---|
Colspan & Rowspan
The colspan attribute of the <th> or <td> element specifies the number of columns the cell should span.
Colspan
| Header 1 | Header 2 | |
|---|---|---|
| Row 1, Column 1 | Row 1, Column 2 | Row 1, Column 3 |
| Row 2, Column 1 | Row 2, Column 2 | Row 2, Column 3 |
Rowspan
The rowspan attribute of the <th> or <td> element specifies the number of rows the cell should span.
| Header 1 | Header 2 |
|---|---|
| Header 3 | |
| Row 1, Column 1 | Row 1, Column 2 |
| Row 2, Column 1 | Row 2, Column 2 |