Which characters are valid in CSS class names/selectors?
What are characters/symbols are allowed within CSS class selectors? I know that the following characters are invalid, but what characters are valid?
~ ! @ $ % ^ & * ( ) + = , . / ' ; : " ? > < [ ] \ { } | ` #
Answer:
You can check directly at the CSS grammar.
Basically1, a name must begin with an underscore (
_
), a hyphen (-
), or a letter(a
–z
), followed by any number of hyphens, underscores, letters, or numbers. There is a catch: if the first character is a hyphen, the second character must2 be a letter or underscore, and the name must be at least 2 characters long.-?[_a-zA-Z]+[_a-zA-Z0-9-]*
Identifiers beginning with a hyphen or underscore are typically reserved for browser-specific extensions, as in
-moz-opacity
.
1 It's all made a bit more complicated by the inclusion of escaped unicode characters (that no one really uses).
2 Note that, according to the grammar I linked, a rule starting with TWO hyphens, e.g.
--indent1
, is invalid. However, I'm pretty sure I've seen this in practice.
COMMENTS