For example: #_id-name {}
and ._class-name {}
I know that in the early days underscores were not allowed at all - as well as double hyphens (--
). But is it OK and would all browsers be able to read/understand a class or an ID if it starts with an _
?
Asked
Active
Viewed 2,529 times
6
-
Possible duplicate: http://stackoverflow.com/a/449000/1696030 Answer: Yes, you can! – Volker E. Apr 25 '14 at 23:09
-
Thanks - it does look like I can: http://www.w3.org/TR/CSS21/syndata.html#vendor-keywords – moonunit7 Apr 25 '14 at 23:21
-
I have seen the other "possible duplicate" but it only talks about using underscores. I want to know if it's OK to *start* and ID or Class name with an underscore... – moonunit7 Apr 27 '14 at 21:59
1 Answers
1
I'm basing my answer on html
rather than just CSS. Documentation:
To summarize, the id must apparently begin with a letter (A-Za-z
) and can have any other letters, numbers, underscore, or dash after that. Practically, you can start the id
with -
or _
and it will work: http://jsfiddle.net/ExplosionPIlls/y6jvs/ but starting with a number does not work.
While these restrictions don't appear to apply to classes which are a CDATA list, practically it seems to work the same: http://jsfiddle.net/ExplosionPIlls/y6jvs/1/
So you get a consistent and future proof browser experience, I would try to avoid doing anything funky with IDs, class names, etc.

Explosion Pills
- 188,624
- 52
- 326
- 405
-
Mmmm... Future proof browser experience is a good thing to keep in mind! – moonunit7 Apr 27 '14 at 22:01
-
Since HTML5 the spec of the id attribute has changed to drop the restrictions you mention. So there is no need to worry about future proofing. "The only requirements left — apart from being unique in the document — are that the value must contain at least one character (can’t be empty), and that it can’t contain any space characters." https://mathiasbynens.be/notes/html5-id-class https://html.spec.whatwg.org/multipage/dom.html#the-id-attribute – Albin May 13 '15 at 23:11
-
1@Albin thank you for pointing to the updated specifications. In the sense that the requirements won't change we don't have to worry about future proofing, but notice that a selector starting with a number for an ID still does not work for CSS or DOM selection even though it is a valid attribute value. – Explosion Pills May 14 '15 at 00:13
-
Indeed. You can still match it using "#\000031" as a selector instead of "#1" however, but it's not very practical. http://jsbin.com/jawojijuza/1/edit?html,css,output – Albin May 14 '15 at 00:53