HTML5 allows almost any value for the id attribute – use wisely
As I mentioned some time ago in Creating valid names with the id attribute, HTML 4.01 is pretty restrictive regarding what values are allowed for
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (“-“), underscores (“_”), colons (“:”), and periods (“.”).
Well, HTML5 changes that by allowing almost any value for the
The value must be unique amongst all the IDs in the element’s home subtree and must contain at least one character. The value must not contain any space characters.
At least one character, no spaces.
This opens the door for valid use cases such as using accented characters. It also gives us plenty of more ammo to shoot ourselves in the foot with, since you can now use
Consider the following HTML:
CSS selector conflicts
To target those elements with CSS, you can’t use the normal syntax:
id values contain characters that have a predefined meaning in CSS, you’ll need to do a bit of work on your CSS selectors for them to work. One way is to use an attribute selector instead of the
Another way is to escape the conflicting characters:
Just as with CSS, you’ll need to escape some characters:
Name elements sensibly
HTML5 gives us more options when naming elements with the
Update: Mathias Bynens explores this issue more in-depth, including a demo page of examples, in The id attribute just got more classy in HTML5.
You should also take a look at Normalization in HTML and CSS for info on how different forms of Unicode can make selectors not match your id values or class names.
- Previous post: Beware of -webkit-text-size-adjust:none
- Next post: Removing title attributes inserted by TextMate’s Hyperlink Helper bundle
Subscribe / follow
DreamHost web hosting
Use the promo code 456BEREASTREET3 to save USD 20 when you sign up for DreamHost