Which characters are valid in CSS class names/selectors?

Introduction

When it comes to writing CSS, class names and selectors play a crucial role in targeting and styling specific elements on a web page. However, not all characters are valid within CSS class names and selectors. In this article, we will explore which characters are allowed and which ones are not.

Valid Characters

In CSS class names and selectors, the following characters are valid:

  • Letters (a-z, A-Z)
  • Digits (0-9)
  • Underscore (_)
  • Hyphen (-)

These characters can be used in any combination to create class names and selectors.

For example:

.my-class1 {
    color: red;
}

#my-element {
    background-color: blue;
}

.element_two {
    font-size: 16px;
}

Invalid Characters

On the other hand, the following characters are invalid and should not be used in CSS class names and selectors:

  • Tilde (~)
  • Exclamation mark (!)
  • At symbol (@)
  • Dollar sign ($)
  • Percent sign (%)
  • Circumflex accent (^)
  • Ampersand (&)
  • Asterisk (*)
  • Left parenthesis (()
  • Right parenthesis ())
  • Plus sign (+)
  • Equal sign (=)
  • Comma (,)
  • Period (.)
  • Slash (/)
  • Apostrophe (')
  • Semicolon (;)
  • Colon (:)
  • Quotation mark (")
  • Question mark (?)
  • Greater than sign (>)
  • Less than sign (<)
  • Left square bracket ([)
  • Right square bracket (])
  • Backslash (\)
  • Left curly brace ({)
  • Right curly brace (})
  • Vertical bar (|)
  • Grave accent (`)
  • Hash (#)

If any of these characters are used in CSS class names or selectors, the CSS rules associated with them may not work as expected.

Examples

Let's take a look at some examples to clarify the usage of valid and invalid characters in CSS class names and selectors.

Valid Class Names and Selectors

.my_class {
    font-weight: bold;
}

.my-element {
    color: green;
}

#element1 {
    background-color: yellow;
}

Invalid Class Names and Selectors

.invalid!class {
    border: 1px solid black;
}

#~element {
    font-size: 18px;
}

.my#selector {
    text-align: center;
}

In these examples, class names and selectors containing invalid characters such as exclamation mark, tilde, and hash result in unexpected behavior or syntax errors.

Summary

In CSS, only letters (a-z, A-Z), digits (0-9), underscore (_) and hyphen (-) are allowed in class names and selectors. All other characters are considered invalid and should be avoided. By following this rule, you can ensure that your CSS styles are applied correctly.

Conclusion

Understanding which characters are valid and invalid in CSS class names and selectors is essential for writing clean and maintainable CSS code. By limiting the characters used in class names and selectors, you can reduce the chances of encountering issues or conflicts with existing CSS rules. Remember to stick to letters, digits, underscore, and hyphen for optimal compatibility and consistent styling across browsers.