CSS Escape Sequences for Identifiers and Strings
Learn how CSS escaping works for identifiers (class names, IDs) and string values. Covers backslash escaping, Unicode code points, CSS.escape() API, and handling special characters in selectors.
Detailed Explanation
CSS Escape Sequences
CSS has its own escaping rules that differ from HTML and JavaScript. Escaping is needed in two contexts: within string values ("..." or '...') and within identifiers (class names, IDs, property names).
Escaping in CSS Identifiers
CSS identifiers (class names, IDs, custom property names) have strict rules. An identifier cannot start with a digit, and many special characters are not allowed without escaping. The escape syntax is a backslash followed by the character:
/* Class name: 1st-item → must escape the leading digit */
.\31 st-item { color: red; }
/* ID: my:id → colon must be escaped */
#my\:id { color: blue; }
/* Class: grid@2x → @ must be escaped */
.grid\@2x { display: grid; }
Unicode Escaping in Identifiers
CSS supports Unicode escapes with a backslash followed by 1-6 hex digits and an optional trailing space:
/* \0041 = "A" */
.\0041 pple { } /* matches class "Apple" */
/* The trailing space is a delimiter, not part of the name */
Escaping in CSS String Values
Inside quoted strings, CSS recognizes:
\\" → literal double quote (in double-quoted string)
\\' → literal single quote (in single-quoted string)
\\\\ → literal backslash
\\n → newline (for content property, etc.)
\\A → newline (hex escape for U+000A)
\\HH → any Unicode character by hex code point
.icon::before {
content: "\2764"; /* ❤ heart character */
}
JavaScript: CSS.escape()
The CSS.escape() API handles identifier escaping programmatically:
CSS.escape("1st-item") // "\\31 st-item"
CSS.escape("my:id") // "my\\:id"
// Use in querySelector:
document.querySelector(`#${CSS.escape(userInput)}`);
Why CSS Escaping Matters
Without CSS.escape(), dynamically constructed selectors with user input can break or be exploited:
// Dangerous — special chars in id break the selector
document.querySelector('#' + userId);
// Safe — properly escaped
document.querySelector('#' + CSS.escape(userId));
Escaping in CSS Custom Properties
Custom properties (--*) are more lenient in what characters they accept, but values used in calc() or url() still follow standard escaping rules.
Use Case
CSS escaping is critical when building dynamic selectors in JavaScript, using data attributes with special characters as selectors, generating CSS with tools like Tailwind or CSS-in-JS libraries, handling user-generated class names in CMS systems, and inserting Unicode icons or special characters via the content property in pseudo-elements.