CLiown
CLiown

Reputation: 13843

Valid CSS classes?

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?

Upvotes: 2

Views: 2763

Answers (4)

Guffa
Guffa

Reputation: 700182

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...

Upvotes: 1

Donut
Donut

Reputation: 112795

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).

Upvotes: 5

bobince
bobince

Reputation: 536339

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.

Upvotes: 5

Marius
Marius

Reputation: 58911

  • .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

Upvotes: 2

Related Questions