Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping characters in CSS class selectors

Tags:

People also ask

Can I use CSS escape?

To fix this is simple enough: You can use the CSS. escape() function to escape a literal string and encodes any Selector specific characters. This includes encoding the : character which is escaped with as \: .

What is the '\ n escape character?

In particular, the \n escape sequence represents the newline character. A \n in a printf format string tells awk to start printing output at the beginning of a newline.

How do you escape characters?

Escape CharactersUse the backslash character to escape a single character or symbol. Only the character immediately following the backslash is escaped.

What does CSS escape do?

The CSS. escape() static method returns a string containing the escaped string passed as parameter, mostly for use as part of a CSS selector.


I'm trying to implement this W3 description of character escapes in CSS class selectors.

I'm running into problems with the abc\20 def syntax that puts a space after the escape sequence to ensure def is not misread as part of the character code.

Specifically, trying to put abc\XY def into an HTML class attribute or into a command like jQuery().addClass('abc\\20 def') (the \\ here is part of the JS string literal syntax; the string value itself has one slash) will both give the element two classes, abc\20 and def.

Is this syntax just badly implemented, and I should stick with the six-digit leading zero form? Or does that document only refer to the escape format in CSS code, and the HTML attribute / jQuery argument require some different form of escaping the space character?

Edit: Thank you very much for explaining, everyone!

I now understand that this syntax only applies to CSS code - not the class names themselves as set in HTML attributes or Javascript.

This also means that characters designated as whitespace can't occur in CSS class values, and no kind of escape mechanism allows them to be added. (Specifically, if I understand correctly, the CSS selector .abc\20 def is valid and selects elements with the class abc def, but is meaningless because no element can have this class.)

For my concrete use case, which involves mapping arbitrary values (which can have white space) to valid class names, I need to define my own escape scheme. Replacing whitespace with - or _ (thanks Praveen) is one possibility; if the mapping needs to be one-to-one, replacing them with six-digit Unicode hex values (eg. "abc def" -> "abc\000020def" is a more robust one.

The important thing to keep in mind is that this replacement affects the class name itself - to refer to the class abc\000020def in CSS, the backslash must be escaped again, to form the selector .abc\\000020def.