Keeping Your Markup Well Formed


“Well-formed” is essentially a new name for an old rule. It simply means that your elements must be nested properly. Consider this example:

<p>Here’s <em>my <strong>opening</em></strong> paragraph!</p>

Here, the em is opened first, and the strong opened second. However, markup follows a “first opened, last closed” rule. Since the em is opened before the strong, it must be closed after the strong’s final tag. If we revise the markup so that it’s well formed, the elements’ nesting order makes a bit more sense:

<p>Here’s <em>my <strong>opening</strong></em> paragraph!</p>

As you’ve no doubt noticed, this concept of proper nesting is an old one. While it’s never been valid to write incorrectly nested markup, it is still quite common in many pages built today. As a result, browsers have become far too tolerant of the tag soup we feed them. Any given browser will have a different strategy in place for how to “fix” this incorrectly nested markup, which can often yield differing results once the page is
rendered. XHTML is a language that explicitly demands structural soundness. By  requiring our markup to be well formed, this stricter document syntax enables us to combat structural inconsistencies in our own code.

Of course, it’s important to remember that “well formed” does not equal “valid.” Consider this example:
<a id=”content”>
<em>
<div class=”item”>
<p>I’m not exactly sure what this means.</p>
<p>...but at least it’s well-formed.</p>
</div>
</em>
</a>

This code is immaculately nested, but it’s far from valid. HTML differentiates between block-level elements (div, p, table, and the like) and inline elements (such as a, em, strong). Inline elements can never contain the block-level elements, making our previous markup invalid. While browsers will be able to read this code correctly, it’s almost certain to cause display errors when the CSS is applied. Depending on the browser, styles applied to the anchor element may or may not cascade down to the text contained in the div. It certainly would be an unpleasant surprise if all of your content suddenly gained the link’s signature underline, or visibly changed when you hovered over it with your mouse.

This is yet another example of the importance of validation. By beginning your document with a DOCTYPE declaration and validating frequently, you can proactively squash layout bugs before they arise. This translates into less debugging time for you, which in turn translates into more time you can spend focusing on your site’s design.