Netscape DevEdge

Skip to: [content] [navigation]

Underscores in class and ID Names

This technical note examines the use of underscores in CSS, and why they should be generally avoided in most circumstances.

It is a fairly common practice in many programming languages to use the underscore character (_) in the place of a "space in variable and function names. For example, a function whose job is to "get the length of a string" might be called get_string_length, and a variable representing the number of people who voted Republican might be voted_Republican.

Given this fact, authors who write CSS often attempt to employ the underscore in a similar fashion when creating class and ID names. This should not be done. Although underscores are, as of this writing, technically permitted in class and ID names, there are many historical and practical reasons why they should be avoided.

The CSS1 specification, published in its final form in 1996, did not allow for the use of underscores in class and ID names unless they were "escaped." An escaped underscore would look something like this:

   p.urgent\_note {color: maroon;}

This was not well supported by browsers at the time, however, and the practice has never caught on. CSS2, published in 1998, also forbade the use of underscores in class and ID names. However, errata to the specification published in early 2001 made underscores legal for the first time. This unfortunately complicated an already complex landscape.

Support realities

Between mistakes in implementation and changes to the specification, browser behavior with regard to underscores is rather convoluted.

Recommendation

Because support is so inconsistent between current browsers as well as older releases, authors are strongly advised to avoid using underscores in class and ID names. A common substitute is the hyphen character (-), as in:

   p.urgent-note {color: maroon;}

Many authors choose instead to use "initial-cap" names such as this:

   p.urgentNote {color: maroon;}

If the initial-cap approach is used, however, remember that class and ID names are also supposed to be case-sensitive. See the tech note "Case Sensitivity in class and id Names" for more details.

A+R