在CSS类选择器中允许使用哪些字符/符号?

我知道下面的字符是无效的,但是哪些字符是有效的呢?

~ ! @ $ % ^ & * ( ) + = , . / ' ; : " ? > < [ ] \ { } | ` #

当前回答

根据Kenan Banks的答案,你可以使用以下两个正则表达式匹配来使字符串有效:

[^a-z0-9A-Z_-]

这是一个反向匹配,选择任何不是字母、数字、破折号或下划线的东西,以便轻松删除。

^-*[0-9]+

它匹配字符串开头的0或1个破折号后面跟着1个或多个数字,也便于删除。

如何在PHP中使用它:

// Make alphanumeric with dashes and underscores (removes all other characters)
$class = preg_replace("/[^a-z0-9A-Z_-]/", "", $class);

// Classes only begin with an underscore or letter
$class = preg_replace("/^-*[0-9]+/", "", $class);

// Make sure the string is two or more characters long
return 2 <= strlen($class) ? $class : '';

其他回答

我们可以在类名中使用所有字符。甚至像#和..我们只需要用\(反斜杠)来转义它们。

test \。123年{ 颜色:红色; } test \ # 123 { 颜色:蓝色; } test \ @123 { 颜色:绿色; } test \ < 123 { 颜色:棕色; } test \ ' 123 { 颜色:紫色; } test \ ~ 123 { 颜色:番茄; } < div class = " test.123”> test.123 < / div > < div class = "测试# 123 " >测试# 123 < / div > < div class = " test@123”> test@123 < / div > < div class = "测试< 123”测试< 123 > < / div > < div class = " 123 " >测试测试的123 < / div > 测试~ < div class = " 123 " >测试~ 123 < / div >

我的理解是,下划线在技术上是有效的。查看:

https://developer.mozilla.org/en/underscores_in_class_and_id_names

“…2001年初发布的规范勘误表首次使下划线合法。”

上面链接的文章说永远不要使用它们,然后给出了一个不支持它们的浏览器列表,至少就用户数量而言,所有这些浏览器都是长冗余的。

对于HTML5和css3,类和id可以以数字开头。

对于那些寻找解决方法的人,您可以使用属性选择器,例如,如果您的类以数字开头。变化:

.000000-8{background:url(../../images/common/000000-0.8.png);} /* DOESN'T WORK!! */

:

[class="000000-8"]{background:url(../../images/common/000000-0.8.png);} /* WORKS :) */

此外,如果有多个类,你需要在选择器中指定它们或使用~=操作符:

[class~="000000-8"]{background:url(../../images/common/000000-0.8.png);}

来源:

https://benfrain.com/when-and-where-you-can-use-numbers-in-id-and-class-names/ 是否有一种变通方法使名称以数字开头的CSS类有效? https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

完整的正则表达式为:

-?(?:[_a-z]|[\200-\377]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])(?:[_a-z0-9-]|[\200-\377]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])*

所以你列出的所有字符,除了“-”和“_”,如果直接使用是不允许的。但是您可以使用反斜杠foo\~bar或使用Unicode符号foo\7E bar来编码它们。