[译] 最详细的 CSS 字符转义处理

原文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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值