By Darryl Hein


2009-01-15 23:37:39 8 Comments

What characters/symbols are allowed within CSS class selectors? I know that the following characters are invalid, but what characters are valid?

~ ! @ $ % ^ & * ( ) + = , . / ' ; : " ? > < [ ] \ { } | ` #

9 comments

@Manny Fleurmond 2019-09-07 14:42:06

Going off of @Triptych's answer, you can use the following 2 regex matches to make a string valid:

[^a-z0-9A-Z_-]

This is a reverse match that selects anything that isn't a letter, number, dash or underscore for easy removal.

^-*[0-9]+

This matches 0 or 1 dashes followed by 1 or more numbers at the beginning of a string, also for easy removal.

How I use it in PHP:

//Make alphanumeric with dashes and underscores (removes all other characters)
$class = preg_replace("/[^a-z0-9A-Z_-]/", "", $class);
//Classes only begin with an underscore or letter
$class = preg_replace("/^-*[0-9]+/", "", $class);
//Make sure the string is 2 or more characters long
return 2 <= strlen($class) ? $class : '';

@Triptych 2009-01-15 23:42:27

You can check directly at the CSS grammar.

Basically1, a name must begin with an underscore (_), a hyphen (-), or a letter(az), 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-]*

In short, the previous rule translates to the following, extracted from the W3C spec.:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-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".

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.

@mipadi 2009-01-15 23:44:41

NB: The W3C says that the use of a leading '-' or '_' should be reserved for vendor-specific CSS extensions (e.g., -moz* classes implemented by Mozilla browsers).

@bobince 2009-01-15 23:59:25

The \-escapes are commonly used, but generally mostly for the purposes of CSS hacks, isolating browsers that don't support them.

@Triptych 2009-01-16 00:02:39

@Paolo - if you stick to the guideline of only using underscores for browser-specific extensions, then there is no harm in IE6 ignoring them

@arxpoetica 2010-10-19 19:16:31

You can use escape notation to represent different characters. This can be useful, say, for targeting the underscore as the first character and having IE6 recognize it, as such: \_

@Daniel Earwicker 2011-06-15 13:49:17

To update @Pim Jager's comment over two years later, according to w3counter.com/globalstats.php IE6 is now used by less than 3% of users, behind IE9 on 4%, IE7 on 9%, IE8 on 22%. All versions of Firefox have 28%, all versions of Chrome have 17%.

@Mathias Bynens 2011-10-17 09:03:37

Everything can be escaped. mothereffingcssescapes.com/#--indent1

@user2864740 2014-02-12 18:57:25

I know this is an old answer, but CSS (at least 2+) allows any {Non-ASCII} character in identifiers.

@Albin 2015-05-13 22:15:30

Regarding the comment by @mipadi: I don't think this a problem in practice (correct me if I'm wrong). Even if I name a class something as unconventional as "-moz-any" (which is not something I plan to do) it still won't clash with ":-moz-any" unless I also happen to write an invalid selector.

@Sheepy 2015-06-02 06:33:49

A rule starting with two hyphens is a CSS variable, which has special meaning and is supported by Firefox.

@eithed 2015-10-12 13:51:48

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+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, 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 - --indent1 is invalid and needs to be escaped as \--indent1 (-- classes break on iOS, for example)

@bigOmega 2016-03-03 19:54:53

On a related note: your grammar allows a single character string? What do you think is the best way to fix that?

@Triptych 2016-03-03 21:25:53

@ bigΩmega I believe single character names are valid as long as they start with a letter or underscore.

@typo 2019-09-24 02:44:33

@Triptych why the plus after the first character set ([_a-zA-Z]+)? If I'm reading the spec right, it can only occur once: either as the first character of the name or the character following the opening hyphen.

@Robert Siemer 2011-07-18 12:32:15

To my surprise most answers here are wrong. It turns out that:

Any character except NUL is allowed in CSS class names in CSS. (If CSS contains NUL (escaped or not), the result is undefined. [CSS-characters])

Mathias Bynens' answer links to explanation and demos showing how to use these names. Written down in CSS code, a class name may need escaping, but that doesn’t change the class name. E.g. an unnecessarily over-escaped representation will look different from other representations of that name, but it still refers to the same class name.

Most other (programming) languages don’t have that concept of escaping variable names (“identifiers”), so all representations of a variable have to look the same. This is not the case in CSS.

Note that in HTML there is no way to include space characters (space, tab, line feed, form feed and carriage return) in a class name attribute, because they already separate classes from each other.

So, if you need to turn a random string into a CSS class name: take care of NUL and space, and escape (accordingly for CSS or HTML). Done.

@Salman A 2014-11-22 16:18:33

The first line of your answer should be "most answers here are outdated/apply only to CSS2".

@Robert Siemer 2014-11-22 23:37:57

@SalmanA The answers I refer to were wrong from the beginning. They neither apply to CSS2.1, CSS2 nor CSS1.

@Pedi T. 2018-06-12 08:03:34

@RobertSiemer good point, I moved my comment to stackoverflow.com/questions/50812118/… (which is never the less related to this topic)

@D.Tate 2016-06-23 17:33:28

For those looking for a workaround, you can use an attribute selector, for instance, if your class begins with a number. Change:

.000000-8{background:url(../../images/common/000000-0.8.png);} /* DOESN'T WORK!! */

to this:

[class="000000-8"]{background:url(../../images/common/000000-0.8.png);} /* WORKS :) */

Also, if there are multiple classes, you will need to specify them in selector I think.

Sources:

  1. https://benfrain.com/when-and-where-you-can-use-numbers-in-id-and-class-names/
  2. Is there a workaround to make CSS classes with names that start with numbers valid?

@Mathias Bynens 2011-07-06 06:41:42

I’ve answered your question in-depth here: http://mathiasbynens.be/notes/css-escapes

The article also explains how to escape any character in CSS (and JavaScript), and I made a handy tool for this as well. From that page:

If you were to give an element an ID value of [email protected]$%^&*()_+-=,./';:"?><[]{}|`#, the selector would look like this:

CSS:

<style>
  #\~\!\@\$\%\^\&\*\(\)\_\+-\=\,\.\/\'\;\:\"\?\>\<\[\]\\\{\}\|\`\#
  {
    background: hotpink;
  }
</style>

JavaScript:

<script>
  // document.getElementById or similar
  document.getElementById('[email protected]$%^&*()_+-=,./\';:"?><[]\\{}|`#');
  // document.querySelector or similar
  $('#\\~\\!\\@\\$\\%\\^\\&\\*\\(\\)\\_\\+-\\=\\,\\.\\/\\\'\\;\\:\\"\\?\\>\\<\\[\\]\\\\\\{\\}\\|\\`\\#');
</script>

@Darryl Hein 2011-07-06 21:38:03

+1 but why would you need to have a class named that!! :P

@Mathias Bynens 2011-07-07 15:12:07

@Darryl Of course, this is a pretty extreme example, but stuff like class="404-error" can be useful.

@flying sheep 2014-07-11 13:44:05

i have an example: i convert a syntax highlighting system’s output to CSS. it has class names like “ISO C++:Types (_t/_type)”. if i only replace whitespace i have valid class names.

@Adamarla 2016-12-14 16:31:00

On your website, you say that the space character can be backslash escaped. When I try it in a class name, I can't get it to work. I notice there is no space in this example. Is it possible?

@Mathias Bynens 2016-12-22 08:22:59

@Adamarla <p class="foo bar"> adds two classes to the p element: foo, and bar. There is no way (that I can think of) to add a classname containing whitespace to an HTML element. The information on how to escape whitespace characters was included because it’s useful to escape such characters in other identifier contexts, e.g. font family names.

@Volksman 2017-01-27 21:14:26

As with most things in life it seems in CSS that there is a difference between "technically legal to the extreme" and "sane".

@Pedi T. 2018-06-13 07:54:35

@MathiasBynens I really would appreciate if you could have a look at my question stackoverflow.com/questions/50812118/… which is related to this one, as you really seem to have an in depth understanding of the specification.

@mofaha 2010-07-31 05:33:54

My understanding is that the underscore is technically valid. Check out:

https://developer.mozilla.org/en/underscores_in_class_and_id_names

"...errata to the specification published in early 2001 made underscores legal for the first time."

The article linked above says never use them, then gives a list of browsers that don't support them, all of which are, in terms of numbers of users at least, long-redundant.

@Marius 2009-10-12 14:04:04

For HTML5/CSS3 classes and IDs can start with numbers.

@Ryan 2010-11-27 21:45:25

Do you have a source for this? Maybe I'm missing something, but the CSS3 selectors spec links to the identifiers definition in the CSS 2.1 spec which doesn't permit leading numbers.

@Mathias Bynens 2011-07-07 15:12:45

@Ryan: Here’s a resource for that: mathiasbynens.be/notes/html5-id-class

@Jamie Pate 2013-04-15 22:04:30

w3.org/TR/2003/WD-css3-syntax-20030813/#characters <--still doesn't permit leading numbers etc (even though it works)

@Oriol 2015-02-16 19:43:11

HTML 5 allows classes and IDs to begin with a number (e.g. class="1a"). However, a CSS identifier can't begin with a number (e.g. .1a won't work). You can escape it, tough (e.g. .\31 a or .\000031a).

@Stickers 2015-02-27 21:15:18

Although it normally works in CSS too, but looks like it's still not official. "Property names and at-rule names are always identifiers, which have to start with a letter or a hyphen followed by a letter, and then can contain letters, numbers, hyphens, or underscores." - w3.org/TR/css3-syntax/#syntax-description

@Bennett McElwee 2015-07-14 23:30:05

@Pangloss But class names aren't property names or at-rule names.

@Stickers 2015-07-15 01:37:52

Not sure what you mean by that @BennettMcElwee but see this demo.

@Stickers 2015-07-15 13:06:36

I think OP also asked for names too @BennettMcElwee "What characters are valid in CSS class names/selectors?", also we're commenting under this very particular answer. I agree with you on the points of attribute selectors, and your demo works.

@Sempie 2015-08-18 07:00:16

Leading numbers don't work. jsfiddle.net/tst1rbv1 tried in IE11, FF39,Chrome44

@Gumbo 2009-01-16 00:05:03

The complete regular expression is:

-?(?:[_a-z]|[\200-\377]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])(?:[_a-z0-9-]|[\200-\377]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])*

So all of your listed character except “-” and “_” are not allowed if used directly. But you can encode them using a backslash foo\~bar or using the unicode notation foo\7E bar.

@flying sheep 2014-07-11 13:46:58

why [\200-\377]? [\178-\1114112] is allowed unescaped in CSS 3.

@James Donnelly 2016-03-18 14:50:34

\377 here is actually wrong. There's a note on the Grammar of CSS2.1's Lexical Scanner section which states: "The "\377" represents the highest character number that current versions of Flex can deal with (decimal 255). It should be read as "\4177777" (decimal 1114111), which is the highest possible code point in Unicode/ISO-10646." It also should be from \240 as well, not \377. I guess this is 7 years old now though so things have probably changed a bit since then.

@James Donnelly 2016-03-18 16:06:29

I believe a more accurate regular expression would be -?(?:[_a-z]|(?![\u0000-\u0239]).*|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])(?:[_a-z0-9-]|(?![\u0000-\u023‌​9]).*|\\[0-9a-f]{1,6‌​}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])*.

@Gumbo 2016-03-18 18:12:38

@JamesDonnelly Please feel free to edit my answer if you think it needs some update.

@Jason S 2009-01-15 23:45:09

Read the W3C spec. (this is CSS 2.1, find the appropriate version for your assumption of browsers)

edit: relevant paragraph follows:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-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".

edit 2: as @mipadi points out in Triptych's answer, there's this caveat, also in the same webpage:

In CSS, identifiers may begin with '-' (dash) or '_' (underscore). Keywords and property names beginning with '-' or '_' are reserved for vendor-specific extensions. Such vendor-specific extensions should have one of the following formats:

'-' + vendor identifier + '-' + meaningful name 
'_' + vendor identifier + '-' + meaningful name

Example(s):

For example, if XYZ organization added a property to describe the color of the border on the East side of the display, they might call it -xyz-border-east-color.

Other known examples:

 -moz-box-sizing
 -moz-border-radius
 -wap-accesskey

An initial dash or underscore is guaranteed never to be used in a property or keyword by any current or future level of CSS. Thus typical CSS implementations may not recognize such properties and may ignore them according to the rules for handling parsing errors. However, because the initial dash or underscore is part of the grammar, CSS 2.1 implementers should always be able to use a CSS-conforming parser, whether or not they support any vendor-specific extensions.

Authors should avoid vendor-specific extensions

@Jason S 2015-05-14 01:04:25

??? "including element names, classes"?

@Albin 2015-05-14 01:25:26

I was referring to your second edit about leading dashes and underscores, but forgot to clarify that. Sorry for the confusion.

Related Questions

Sponsored Content

15 Answered Questions

[SOLVED] Is there a "previous sibling" selector?

  • 2009-11-30 04:06:36
  • Jourkey
  • 603875 View
  • 1236 Score
  • 15 Answer
  • Tags:   css css-selectors

29 Answered Questions

[SOLVED] Can a CSS class inherit one or more other classes?

  • 2009-06-30 19:10:57
  • Joel Martinez
  • 586851 View
  • 695 Score
  • 29 Answer
  • Tags:   css

19 Answered Questions

[SOLVED] Is it possible to apply CSS to half of a character?

9 Answered Questions

[SOLVED] Can I write a CSS selector selecting elements NOT having a certain class or attribute?

31 Answered Questions

[SOLVED] Is there a CSS parent selector?

  • 2009-06-18 19:59:36
  • jcuenod
  • 1806449 View
  • 2949 Score
  • 31 Answer
  • Tags:   css css-selectors

5 Answered Questions

[SOLVED] What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

17 Answered Questions

[SOLVED] CSS selector for first element with class

  • 2010-04-26 22:51:13
  • Rajat
  • 913034 View
  • 869 Score
  • 17 Answer
  • Tags:   css css-selectors

3 Answered Questions

[SOLVED] css selector to match an element without attribute x

11 Answered Questions

[SOLVED] What does the "+" (plus sign) CSS selector mean?

  • 2009-07-16 19:26:50
  • gday
  • 300729 View
  • 724 Score
  • 11 Answer
  • Tags:   css css-selectors

7 Answered Questions

[SOLVED] CSS '>' selector; what is it?

  • 2010-12-16 10:39:47
  • Bojangles
  • 305698 View
  • 549 Score
  • 7 Answer
  • Tags:   css css-selectors

Sponsored Content