CSS类名/选择器中哪些字符是有效的?

1339

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

我知道以下字符是无效的,但是哪些字符是有效的

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

8
相关问题:https://dev59.com/mXE85IYBdhLWcg3wXCS1 - BalusC
42
UTF8字符怎么办?比如我可能会输入希腊语。 - GorillaApe
12
在类名中使用特殊字符时需要进行转义。在CSS文件中,您可以通过转义反斜杠来定义一个.hello/world类: .hello\2fworld, hello\2f worldhello\/world - wyqydsyq
2
另一个相关的问题,不是关于“名称语法”,而是关于“类属性语法”的问题,当表达多个名称时。 - Peter Krauss
6
您可以使用表情符号。https://www.npmjs.com/package/postcss-modules-emoji-classname - Kevin Suttle
显示剩余5条评论
11个回答

0
根据 Kenan Banks's answer,您可以使用以下两个正则表达式匹配来使字符串有效:
[^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 : '';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接