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
  • 100,586
  • 22
  • 140
  • 187
CLiown
  • 13,177
  • 46
  • 121
  • 202

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
  • 514,530
  • 102
  • 640
  • 820
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
  • 103,927
  • 20
  • 129
  • 143
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
  • 55,927
  • 31
  • 124
  • 146
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
  • 666,277
  • 106
  • 705
  • 986