CSS

2016-02-20 16:16

CSS中使用数字作为类名或ID

刚才群里有位群友 css 中字体大小定义不起作用。最后发现是类名用数字开头的。

以前自己写代码也没有用数字开头的习惯,所以一直没发现这问题。感谢“♂ -ing”指出。

研究了下,发现W3C中有这么条规定:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier “B&W?” may be written as “B\&W\?” or “B\26 W\3F”.

大概意思就是 CSS 中,html元素的name、class还有id的值只允许以下字符:[a-zA-Z0-9]、ISO 10646字符U+00A0版本及以上字符、加上破折号(-)跟下划线(_),而且不能以数字、两个破折号或一个破折号后跟数字开头,允许使用转义字符或ISO 10646编码的数字。比如B&W?要写成B\&W\?(转义) 或者B\26 W\3F(ISO 10646编码)。

也就是说,一般情况下html元素的name、class还有id的值不能以数字开头。

但如果你非要用数字开头也不是没有办法,只要把作为首字母的数字替换为相应的ISO 10646编码就可以了。例如:

  1. <div id="123"></div>

上面的代码,在 CSS 中应该写成:

  1. div.\31 23 { width: 500px; height: 500px;}

下面是0-9对应的ISO 10646字符编码:
|0|1|2|3|4|5|6|7|8|9|
| :——————: | :——————: | :——————: | :——————: | :——————: | :——————: | :——————: | :——————: | :——————: | :——————: |
|\30|\31|\32|\33|\34|\35|\36|\37|\38|\39|

你可能还喜欢...

  1. Z Z

    火前留名,有一股钻研的味道。

添加新评论