Which characters are valid in CSS class names/selectors?

In this tutorial, we will learn how to check which characters are valid in CSS class names/selectors with the help of examples? By Shahnail Khan Last updated : July 12, 2023

We create classes by using a class attribute in HTML. The class attribute specifies one or more class names for an element. The class names are used by CSS & JavaScript to access and style specific elements. We need to follow the standard naming convention for HTML/CSS classes for writing class names. Some characters are not valid in CSS class names/selectors. In this article, we will see both the valid and invalid characters in CSS class names.

Naming conventions to check characters are valid in CSS class names/selectors

  1. The class name should consist of any combination of lowercase characters(a-z), uppercase characters(A-Z), a hyphen (-), underscore (_) and digits (0-9).
  2. The class name shouldn't start with a digit.
  3. The following characters are invalid in CSS: ~, @, #, $, %, ^, &, *, (,), {}, |, \, [],?, /,<,>, ",',+, =

Note: All the characters are acceptable by HTML. To style with CSS, you must follow naming conventions.

Example to check characters are valid in CSS class names/selectors

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title> Characters valid in CSS</title>
   </head>
   
   <style>
      .INCLUDEHELP, .includehelp,._IncludeHelp,.-includehelp{
      font-size: x-large;
      background-color: lightgreen;
      font-style: italic;
      border: 2px solid black;
      }
      .1stclass,.:includehelp{
      border: 2px solid black;
      }
   </style>
   
   <body>
      <div class="INCLUDEHELP">
         class name starting with uppercase character is valid
      </div>
      <div class="includehelp">
         class name starting with a lowercase character is valid
      </div>
      <div class="_IncludeHelp">
         class name starting with an underscore is valid
      </div>
      <div class="1stclass">
         class name starting with a number is not valid
      </div>
      <div class="-includehelp">
         class name starting with a dash is valid
      </div>
      <div class=":includehelp">
         class name staring with a colon(:) is not valid
      </div>
</html>

Output

Example | class names selectors

As you can see, the class names which follow naming conventions are accessed by CSS and so the elements of these classes are styled. The classes named "1stclass" and ":includehelp" don't follow naming conventions, so they are not accessed by CSS.

CSS Examples »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.