Explain Codes LogoExplain Codes Logo

What are all the valid self-closing elements in XHTML (as implemented by the major browsers)?

html
self-closing-tags
xhtml-specification
mime-types
Anton ShumikhinbyAnton Shumikhin·Mar 10, 2025
TLDR

Here are XHTML self-closing tags widely acknowledged:

  • Br: <br /> (line break)
  • Hr: <hr /> (horizontal rule)
  • Img: <img src="..." alt="..." /> (image)
  • Input: <input type="..." /> (form input)
  • Link: <link rel="stylesheet" href="..." /> (external resource link)
  • Meta: <meta name="..." content="..." /> (metadata)

Remember to add a space before the closing / for XHTML compatibility.

XHTML vs HTML: the big debate

When dealing with self-closing tags, the key factor is whether your document is treated as HTML or XHTML. As similar as they may seem, they function differently under the hood.

Handling MIME types for document parsing

Generally, the MIME type determines if a document is parsed as HTML or XHTML, irrespective of the DOCTYPE.

XHTML documents sent right

If you're writing in XHTML, ensure your documents are served with application/xhtml+xml MIME type. Serving them with text/html confuses the browser to parse them as HTML, failing the self-closure expectation.

The scoring shot: self-closing all the way in XHTML

In XHTML, if an element doesn't require content, feel free to go with the self-closing form. This follows the strict XHTML specification, letting you code clean.

How not to mess up: best practices and pitfalls

A slight misunderstanding can turn your code haywire. Be aware of these common issues:

Serving XHTML like an HTML dish

Serving XHTML with a text/html MIME type is a disaster - the browser switches to HTML mode and does a facepalm every time it sees a supposed self-closing tag.

Choose wisely: Content-Type > DOCTYPE

Browsers check the Content-Type HTTP header to decide whether to parse the document as HTML or XHTML. Your DOCTYPE declaration at the top of the document, on the other hand, gathers dust.

Fit into the web ecosystem

Web standards are like laws of programming nature:

Following the XHTML spec

Keep referring to XHTML specifications to ensure you're on the right track with self-closing tags.

Validate, validate, validate

Cross-check your XHTML documents using validators, e.g., W3C's Markup Validation Service. This can ensure your usage of self-closing elements is spot on, and prevent Janitor Browser from cleaning up your messy tags.

Brace for the future!

Adopting solid practices like knowing when to self-close tags in XHTML prepares you for an easier transition when future XML-based tech knocks on the door 💪