HTML: The Table Element
Overview
HTML table elements are used to create visual representations of tabular data, allowing users to quickly compare and analyze different values.
"The table
HTML element represents tabular data — that is, information presented in a
two-dimensional table comprised of rows and columns of cells containing data." - MDN
Prepare
- Reference: The Table Element - MDN
Activity Instructions
- In your browser, navigate to the "Try-It" section on the MDN page: The Table Element.
- Ponder the HTML and CSS used to create the example table.
- You will be modifying the existing table shown below. to look like this with a new "Department" column.
- In the HTML panel, add another column to the left of the existing table header (
<thead>
) section using a<th>
and a column scopescope="col"
. - Insert the heading of "Department" into that new heading cell.
Check Your Understanding
<thead> <tr> <th scope="col">Department</th> <th scope="col">Person</th> <th scope="col">Most interest in</th> <th scope="col">Age</th> </tr> </thead>
- Add another table heading cell (
<th>
) to the existing first row (<tr>
) of the table's body (<tbody>
) - Insert the text of "Accounting" into the new cell.
- Modify the new cell to span all four rows in the table body using
rowspan
.Check Your Understanding
<tbody> <tr> <th rowspan="4">Accounting</th> <th scope="row">Chris</th> <td>HTML tables</td> <td>22</td> </tr>
Why do we want to use
rowspan
on that first cell?What is the role of the
scope
attribute in the table heading cells?Providing a
scope
to a header cell in a table, indicates whether it applies to a row or column. Using the scope attribute appropriately improves the accessibility and usability of tables for all users, especially those relying on assistive technologies like screen readers. - Now notice that the
<tfoot>
content is not lined up correctly. How can you fix this layout issue?Check Your Understanding
The<tfoot> <tr> <th scope="row" colspan="3">Average age</th> <td>33</td> </tr> </tfoot>
colspan
value was changed from 2 to 3. - Change the style of the table to use a black background in the table header row with white text.
Check Your Understanding
thead th { background-color: #000; /* This is shorthand HEX notation for #000000 */ color: #fff; }
- Change the style of the table caption to be italic.
Check Your Understanding
caption { caption-side: bottom; padding: 10px; font-weight: 700; font-style: italic; }
Note that the font-weight value was changed from the semantic "bold" to "700". Using 700 is more precise and explicit, especially if you're working with a font that has multiple weights.
A complete example of the modification is provided here: MDN Table Try It Modification - CodePen