Optional Tags

The HTML specification allows us to omit some tags. Several end tags are optional, for instance </p> and </li>, but they don’t matter from a CSS point of view. What is important to consider is that in HTML 4, the start tags are optional in four instances: <html>, <head>, <body>, and <tbody>. The corresponding elements will exist in the document object model (DOM) tree whether or not the tags are present in the markup. It’s now considered best practice to include these tags explicitly, but an HTML document can be valid without them.

The <html>, <head>, and <body> tags aren’t optional in XHTML; they must be included explicitly in the markup. It’s permissible, even in XHTML, to omit the <tbody> and </tbody> tags in simple tables, not because the tags are optional—there’s no such thing as an optional tag in XML—but because XHTML allows two content models for the table element type.

Whereas HTML regards the tbody element tags as optional (thereby making them implicit), the XHTML specification states that a table must contain either one or more tbody elements, or one or more tr elements (after any optional caption, col, colgroup, thead, and tfoot elements).

The important difference is that, in an XHTML document, a table element that lacks <tbody> and </tbody> tags won’t contain a tbody element node in the DOM tree. In HTML, the tbody element will be present in the DOM tree whether or not the tags are present.

This variation can affect our use of CSS in specific cases. Consider the following CSS rules, which set a medium font weight for header cells in the table body (presumably row headers), and a bold font for other header cells (for example, those in a thead element):

th {
  font-weight: bold;
}
tbody th {
 font-weight: normal;
}

Now, let’s look at two different ways to write the markup for a simple table:

<table>
  <tbody>
    <tr>
      <th>Blue Widgets</th>
      <td>$12.95</td>
      <td>3 lbs</td>
    </tr>
    ⋮ more table rows
  </tbody>
</table>

For the table above, row headings like “Blue Widgets” will have a normal font weight, regardless of whether the document uses HTML or XHTML, since the markup includes explicit <tbody> and </tbody> tags.

Here’s another example; this one omits the <tbody> tags:

<table>
  <tr>
    <th>Blue Widgets</th>
    <td>$12.95</td>
    <td>3 lbs</td>
  </tr>
  ⋮ more table rows
</table>

The table above is a little different. In an HTML document, the row headings will have a normal font weight: because the tbody element will be present in the DOM tree, the second selector will match the th elements.

In an XHTML document, however, the row headings will be bold, because only the first selector matches any th elements. Omitting the <tbody> and </tbody> tags means that a tbody element won’t appear in the DOM tree, so the second selector won’t match the th elements in this table.

User-contributed notes

Related Products