Better ways to organize data - Tables

HTML provides us with methods to present information. In the intro HTML class, simple tags were discussed that provided simple formating and initial organization options (e.g. headers, paragraphs, lists). Many times, the data we wish to present can easily be converted into a table or spreadsheet. HTML provides us the <table> element to help us organize such data.

<table> <caption> This is the overall title of the table </caption> <thead> <tr><th>tr starts a row</th><th>th is a table headerdata cell</th></tr> </thead> <tbody> <tr><td>tr starts a row</td><td><u>td</u> is a table data row</td></tr> </tbody> <tfoot> <tr><th>footer1</th><th>footer2</th></tr> </tfoot> </table>

Above you can see that a table can consist of 4 parts. The caption/title, header, body, and footer. Note that the header, body, and footer elements are optional, and a fully functional table can be created from just the <table>, <tr>, and <td> tags.

Initial thoughts about Cascading Style Sheets (CSS)

By default, the <table> element creates a table without borders. To show the border, you need some CSS. Place the code below in the <head> element of your page, to show the borders (that is an embedded stylesheet, and we'll learn more about stylesheets later in the course).

<head> <style> table, td, th { border: 1px solid black; } </style> </head>

Cell Sizes and Spanning Rows or Columns

The size of the individual cells in a table will automatically resize based upon their content. This means that the content in a single cell can have an effect on the size of both the associated row and column. Additionally, just like all other HTML content, you may put arbitrary HTML within each cell. Modify the content of the example table above (add a picture, or increase the amount of text to quickly see the effects)

We can use the rowspan and colspan attributes to modify <th> and <td> elements as shown below. The rowspan attribute will make the corresponding cell to span multiple rows (merges together the cells in as many rows as specified by the rowspan atribute) and the colspan attribute will make the corresponsing cell to span multiple columns (it will merge as many columns as specified by the colspan attribute).

<table> <tr> <td>a cell</td> <td rowspan="2">this takes up two rows</td> </tr> <tr> <td>another cell</td> </tr> <tr> <td colspan="2">this takes up two columns</td> </tr> </table>

Practice Problems

  1. Build the HTML to build the table shown below
    table problem 0
  2. Build the HTML to build the table shown below
    table problem 1
  3. Build the HTML to build the table shown below
    table problem 2