Categories
HTML Tutorials

Denoting the headings and the table body

The tbody element denotes the set of rows that comprise the body of our table—as opposed to the header and footer rows, which you denote with the thead and tfoot elements and which we’ll get to shortly. As a related aside, most browsers automatically insert the tbody element when they process a table element, even if it has not been specified in the document. This means that CSS selectors that assume the table layout is as written can fail. For example, a selector such as table > tr won’t work, because the browser has inserted a tbody element between the table and tr elements. To address this, you must use a selector such as table > tbody > tr, table tr (no > character), or even just tbody > tr. The thead element defines one or more rows that are the column labels for a table element. Without the thead element, all of your tr elements are assumed to belong to the body of the table.

The below code shows the addition of the thead and tbody elements to the example table, and the more flexible CSS selectors you can use as a consequence.

<html>
  <head>
    <title>Example</title>
    <meta name="author" content="Adam Freeman"/>
    <meta name="description" content="A simple example"/>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    <style>
      thead th { 
        text-align:left; 
        background:grey; 
        color:white
      }
      tbody th { 
        text-align:right; 
        background: lightgrey; 
        color:grey
      }
    </style>
  </head>
  <body>
    <table>
      <thead>
        <tr>
          <th>Rank</th>
          <th>Name</th>
          <th>Color</th>
          <th>Size</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th>Favorite:</th>
          <td>Apples</td>
          <td>Green</td>
          <td>Medium</td>
        </tr>
        <tr>
          <th>2nd Favorite:</th>
          <td>Oranges</td>
          <td>Orange</td>
          <td>Large</td>
        </tr>
        <tr>
          <th>3rd Favorite:</th>
          <td>Pomegranate</td>
          <td>A kind of greeny-red</td>
          <td>Varies from medium to large</td>
        </tr>
      </tbody>
    </table>
  </body>
</html>

This may not seem like a big deal, but the structure you added to the table makes dealing with the different kinds of cells much easier and less likely to fail if you modify the design of the table.