Explain Codes LogoExplain Codes Logo

What characters are allowed in an HTML attribute name?

html
responsive-design
best-practices
xml
Alex KataevbyAlex Kataev·Oct 24, 2024
TLDR

HTML attribute names start with a letter or underscore (_), with subsequent characters including letters, digits, underscores (_), hyphens (-), and periods (.). The room of doom (invalid characters) includes whitespace, " ' = < >. For wider compatibility, treat colons :` and nonstandard characters like raw eggs in a microwave - enjoy from a distance.

<!-- CSI: Attribute - Following the rules always pays off --> <div data-custom="value" valid-name2="value"></div>

Meanwhile, sticking to alphanumeric chars and common symbols, you're playing it safer than a password manager.

Decoding the specification

HTML5, like a good mystery novel, has more layers than meets the eye. The HTML5 parser spec is our detective, leading us to understand why some characters should never make an appearance in attribute names – enter the notorious ASCII control characters, meddling with parsing and scripting.

In HTML, capital punishment refers to treating case sensitivity as nonexistent. Both 'data-user' and 'DaTa-UsEr' are seen as doppelgängers. Nevertheless, using lowercase is advised, promoting readability and consistency.

In our story, the custom elements are the newcomers but are expected to obey the law of the land - the XML Name restrictions permitting alphanumeric characters, underscores (_), hyphens (-), and periods (.). And remember, custom data attributes wear a 'data-' badge.

Let's face reality, while the HTML5 spec gives you a go-ahead, avoid being the town rebel. Stick to a subset of characters lest we customize ourselves into a corner.

HTML vs. XHTML: The Duel

HTML - The Elastic Band

While HTML, shows a certain tolerance akin to an overly forgiving teacher, aiming to be a straight-A student always pays off. Sticking close to the W3C specification, you're not only securing today's success but also keeping your future catastrophe-free.

XHTML - The Steel Frame

Now, if you're playing the XHTML game, an application of XML, you've stepped into stricter territory. The XML specification is your code-of-conduct, with zero spaces for mistakes. The daring among us might flirt with characters like colons (:), but remember trapeze performers have nets, we don't.

Custom attributes: The frontier town

The Settlers

Custom elements are like settlers in a new land, they should respect the established settlements, or built-in elements, keeping our attribute town civilized.

This town isn't big enough

Though HTML5 allows for innovation with data- attributes*, they risk turning into wild west shoot-outs with interoperability issues. Being law-abiding here doesn't mean boring, it means being smart.