2

Are the following valid class names?

.text-moretext

.text&text

.text_text

.text(text)

I suppose is any CSS class allowed to contain special chracters?

Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192
CLiown
  • 13,665
  • 48
  • 124
  • 205

4 Answers4

5

Yes, you can use any character in a class name except for whitespace which separates class names: class is a cdata-list. Some characters would need escaping. For HTML:

<div class="text&amp;moretext"> ... </div>

and in a selector:

.text\&text { ... }
.text\(text\) { ... }

It's generally best to avoid where possible for coding sanity, but yes you can do it if you need to.

bobince
  • 528,062
  • 107
  • 651
  • 834
5

According to the CSS Specification, Section 4.1.3:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A1 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".

So, .text-moretext and .text_text are valid identifiers (and can be used as class names), while .text&text and .text(text) are not (although as @bobince pointed out, you can escape the special characters in order to use them as part of an identifier).

Donut
  • 110,061
  • 20
  • 134
  • 146
2
  • .text-moretext is allowed
  • .text&text is not allowed, because the & is a special character in HTML
  • .text_text is allowed
  • .text(text) is not allowed
Marius
  • 57,995
  • 32
  • 132
  • 151
1

Characters A-Z, a-z, digits, hyphen (-) and underscore (_) are the common characters allowed in an class name. (There are some more culture-specific characters allowed, but no other punctuation.)

So, text-moretext and text_text are valid class names.

When in doubt, be restrictive with punctuation and exotic characters. Some older browsers might not always get it right...

Guffa
  • 687,336
  • 108
  • 737
  • 1,005