原文:CSS character escape sequences
作者:Mathias 发表时间:12th July 2010
译者:西楼听雨 发表时间: 2018/11/5 (转载请注明出处)
查看原文 When writing CSS for [markup with weird `class` or `id` attribute values](https://mathiasbynens.be/notes/html5-id-class), you need to [consider](https://www.w3.org/TR/CSS21/syndata.html#characters) some [rules](https://www.w3.org/International/questions/qa-escapes#cssescapes). For example, you can’t just use `## { color: #f00; }` to target the element with `id="#"`. Instead, you’ll have to escape the weird characters (in this case, the second `#`). Doing so will cancel the meaning of special CSS characters in identifiers and allows you to refer to characters you cannot easily type out, like crazy Unicode symbols.
There are some other cases where you might want or need to escape a character in CSS. You could be writing a selector for a funky id
, class
, attribute or attribute value, for example; or maybe you want to insert some weird characters using the content
property without changing your CSS file’s character encoding.
当为一些 class 或 id 属性值比较奇怪的标签 编写 CSS 样式时,我们需要考虑到一些限制。例如:不能直接使用 ## { color: #foo; }
来匹配到 id="#"
这样的元素;而是应该将这些怪异的字符进行转义(这个例子中,指第二个“#”),这样做就可以消除标识符中包含的特殊 CSS 字符的涵义,还可以引用到不能简单敲出来的字符,如令人抓狂的 Unicode 符号。
还有一些其他情况你可能或需要在 CSS 中使用转义来对一个字符进行转义。举个例子:你可能会为一个有趣的 id 、class、属性或属性值写一个选择器;或者你想要在不改变 CSS 文件的字符编码的条件下使用 content
属性表达式来插入一个奇怪的字符。
CSS 中的标识符和字符串
查看原文 [The spec](http://dev.w3.org/csswg/css-syntax/#ident-token-diagram) defines *identifiers* using a token diagram. They may contain the symbols from `a` to `z`, from `A` to `Z`, from `0` to `9`, underscores (`_`), hyphens `-`, non-ASCII symbols or escape sequences for any symbol. They cannot start with a digit, or a hyphen (`-`) followed by a digit. Identifiers require at least one symbol (i.e. the empty string is not a valid identifier).The grammar for identifiers is used for various things throughout the specification, including element names, class names, and IDs in selectors.
The spec definition for strings says that strings can either be written with double quotes or with single quotes. Double quotes cannot occur inside double quotes, unless escaped (e.g., as '\"'
or as '\22'
). The same goes for single quotes (e.g., "\'"
or "\27"
). A string cannot directly contain a newline. To include a newline in a string, use an escape sequence representing the line feed character (U+000A), such as "\A"
or "\00000a"
. Newlines can also be represented as "\D \A "
(CRLF), "\D "
(i.e. \r
in other languages), or "\C "
(i.e. \f
in other languages)