Writing well-formed XHTML is good to strive for, because it:
- avoids layout issues
- minimises cross-browser bugs
- improves readability of code
- improves debugging
What is XHTML?
XHTML is a stricter and clearer version of HTML1.
There are a few new rules, but here are the basics:
- Tags must be lowercase
- Tags must be closed (all tags have matching end tags)*
- Tags must be well formed and properly nested
- Attributes must also be lowercase
- Attributes must be surrounded by quotation marks
* Empty XHTML tags are “self closed” (for example br and img). In XHTML, these are closed by a forward slash (“/”) before the ending brace, eg: <br />
An Example
Here is an example of poorly written XHTML:
<em><A HREF=http://www.google.com CLASS=Menulink>Google</A><BR><BR>
This example shows:
- tags and attributes that are uppercase
- tags nested incorrectly – the italics (
em) and link (a) tag overlap - unclosed tags – the italics tag and the line break (
br) tags - attributes that are not surrounded by quotation marks – the link element’s
hrefandclassattributes - attributes that are not lowercase – the link element’s
classattribute
Here is how it can be improved:
<a href="http://www.google.com" class="menulink"><em>Google</em></a> <br /><br />
In this example, all tags and attributes are lowercase, nested and closed correctly.
Writing Better HTML: Removing Hardcoded Presentation
(from now on, HTML will be used as the generic term for XHTML)
While the second example is much better, there are still a few ways it could be improved. Emphasis (em) tags are used for italic text, while the line break (br) tags add extra space. Both of these are forms of “hardcoded presentation” – these HTML tags have been added to make the page display a certain way.
Once upon a time, this was the only way to control the presentation of HTML. However, another technology known as CSS now serves this purpose, and these extra HTML tags should be avoided.
Separating the form (presentation) of HTML from its function (markup structure), allows for cleaner and clearer HTML that is more flexible in its presentation.
Looking again at our example, it can be further improved to:
<div class="menulink"><a href="http://www.google.com">Google</a></div>
Presentation tags have been removed, and a surrounding “container” element has been added, allowing presentation decisions such as font styles and spacing to be applied through CSS.
