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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/448981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 20:13:05  来源:igfitidea点击:

Which characters are valid in CSS class names/selectors?

csscss-selectors

提问by Darryl Hein

What characters/symbols are allowed within the CSSclass selectors?
I know that the following characters are invalid, but what characters are valid?

CSS类选择器中允许使用哪些字符/符号?
我知道以下字符无效,但哪些字符有效

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

采纳答案by Triptych

You can check directly at the CSS grammar.

您可以直接查看CSS 语法

Basically1, a name must begin with an underscore (_), a hyphen (-), or a letter(az), followed by any number of hyphens, underscores, letters, or numbers. There is a catch: if the first character is a hyphen, the second character must2be a letter or underscore, and the name must be at least 2 characters long.

基本上为1,名称必须以下划线 ( _)、连字符 ( -) 或字母 ( az)开头,后跟任意数量的连字符、下划线、字母或数字。还有一个问题:如果第一个字符是一个连字符,第二个字符必须2是字母或下划线,并且名称必须至少2个字符长。

-?[_a-zA-Z]+[_a-zA-Z0-9-]*

In short, the previous rule translates to the following, extracted from the W3C spec.:

简而言之,从W3C 规范中提取的先前规则转换为以下规则。

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-z0-9] and ISO 10646 characters U+00A1 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, 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 中,标识符(包括元素名称、类和选择器中的 ID)只能包含字符 [a-z0-9] 和 ISO 10646 字符 U+00A1 及更高,加上连字符 (-) 和下划线 (_) ; 它们不能以数字开头,也不能以连字符后跟数字开头。标识符还可以包含转义字符和任何 ISO 10646 字符作为数字代码(参见下一项)。例如,标识符“B&W?” 可以写成“B\&W\?” 或“B\26 W\3F”。

Identifiers beginning with a hyphen or underscore are typically reserved for browser-specific extensions, as in -moz-opacity.

以连字符或下划线开头的标识符通常保留用于特定于浏览器的扩展,如-moz-opacity.

1It's all made a bit more complicated by the inclusion of escaped unicode characters (that no one really uses).

1由于包含转义的 unicode 字符(没有人真正使用),这一切都变得更加复杂了。

2Note that, according to the grammar I linked, a rule starting with TWO hyphens, e.g. --indent1, is invalid. However, I'm pretty sure I've seen this in practice.

2请注意,根据我链接的语法,以两个连字符开头的规则(例如--indent1)是无效的。但是,我很确定我已经在实践中看到了这一点。

回答by Robert Siemer

To my surprise most answers here are wrong. It turns out that:

令我惊讶的是,这里的大多数答案都是错误的。事实证明:

Any character except NUL is allowed in CSS class names in CSS.(If CSS contains NUL (escaped or not), the result is undefined. [CSS-characters])

CSS 中的 CSS 类名称中允许使用除 NUL 之外的任何字符。(如果 CSS 包含 NUL(转义与否),则结果未定义。[ CSS-characters])

Mathias Bynens' answerlinks to explanationand demosshowing how to use these names. Written downin CSS code, a class name may need escaping, but that doesn't change the class name. E.g. an unnecessarily over-escaped representation will look different from other representations of that name, but it still refers to the same class name.

Mathias Bynens 的回答链接到解释演示,显示如何使用这些名称。在 CSS 代码中,类名可能需要转义,但这不会改变类名。例如,一个不必要的过度转义的表示看起来与该名称的其他表示不同,但它仍然引用相同的类名。

Most other (programming) languages don't have that concept of escaping variable names (“identifiers”), so all representations of a variable have to look the same. This is not the case in CSS.

大多数其他(编程)语言没有转义变量名称(“标识符”)的概念,因此变量的所有表示形式必须看起来相同。在 CSS 中情况并非如此。

Note that in HTML there is no way to include space characters (space, tab, line feed, form feed and carriage return)in a class name attribute, because they already separate classes from each other.

请注意,在 HTML 中,无法在类名属性中包含空格字符(空格、制表符、换行、换页和回车),因为它们已经将类彼此分开。

So, if you need to turn a random string into a CSS class name: take care of NUL and space, and escape (accordingly for CSS or HTML). Done.

因此,如果您需要将随机字符串转换为 CSS 类名:请注意 NUL 和空格,并转义(相应地用于 CSS 或 HTML)。完毕。

回答by Mathias Bynens

I've answered your question in-depth here: http://mathiasbynens.be/notes/css-escapes

我已经在这里深入回答了您的问题:http: //mathiasbynens.be/notes/css-escapes

The article also explains how to escape any character in CSS (and JavaScript), and I made a handy toolfor this as well. From that page:

这篇文章还解释了如何在 CSS(和 JavaScript)中转义任何字符,我也为此制作了一个方便的工具。从该页面:

If you were to give an element an ID value of ~!@$%^&*()_+-=,./';:"?><[]{}|`#, the selector would look like this:

CSS:

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

JavaScript:

<script>
  // document.getElementById or similar
  document.getElementById('~!@$%^&*()_+-=,./\';:"?><[]\{}|`#');
  // document.querySelector or similar
  $('#\~\!\@\$\%\^\&\*\(\)\_\+-\=\,\.\/\\'\;\:\"\?\>\<\[\]\\\{\}\|\`\#');
</script>

如果你给一个元素一个 ID 值~!@$%^&*()_+-=,./';:"?><[]{}|`#,选择器看起来像这样:

CSS:

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

JavaScript:

<script>
  // document.getElementById or similar
  document.getElementById('~!@$%^&*()_+-=,./\';:"?><[]\{}|`#');
  // document.querySelector or similar
  $('#\~\!\@\$\%\^\&\*\(\)\_\+-\=\,\.\/\\'\;\:\"\?\>\<\[\]\\\{\}\|\`\#');
</script>

回答by Jason S

Read the W3C spec. (this is CSS 2.1, find the appropriate version for your assumption of browsers)

阅读W3C 规范。(这是 CSS 2.1,找到适合您的浏览器假设的版本)

edit: relevant paragraph follows:

编辑:相关段落如下:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-z0-9] and ISO 10646 characters U+00A1 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, 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 中,标识符(包括元素名称、类和选择器中的 ID)只能包含字符 [a-z0-9] 和 ISO 10646 字符 U+00A1 及更高,加上连字符 (-) 和下划线 (_) ; 它们不能以数字开头,也不能以连字符后跟数字开头。标识符还可以包含转义字符和任何 ISO 10646 字符作为数字代码(参见下一项)。例如,标识符“B&W?” 可以写成“B\&W\?” 或“B\26 W\3F”。

edit 2: as @mipadi points out in Triptych's answer, there's this caveat, also in the same webpage:

编辑 2:正如@mipadi 在 Triptych 的回答中指出的那样,在同一个网页中也有这个警告

In CSS, identifiers may begin with '-' (dash) or '_' (underscore). Keywords and property names beginning with '-' or '_' are reserved for vendor-specific extensions. Such vendor-specific extensions should have one of the following formats:

'-' + vendor identifier + '-' + meaningful name 
'_' + vendor identifier + '-' + meaningful name

Example(s):

For example, if XYZ organization added a property to describe the color of the border on the East side of the display, they might call it -xyz-border-east-color.

Other known examples:

 -moz-box-sizing
 -moz-border-radius
 -wap-accesskey

An initial dash or underscore is guaranteed never to be used in a property or keyword by any current or future level of CSS. Thus typical CSS implementations may not recognize such properties and may ignore them according to the rules for handling parsing errors. However, because the initial dash or underscore is part of the grammar, CSS 2.1 implementers should always be able to use a CSS-conforming parser, whether or not they support any vendor-specific extensions.

Authors should avoid vendor-specific extensions

在 CSS 中,标识符可以以“-”(破折号)或“_”(下划线)开头。以“-”或“_”开头的关键字和属性名称保留用于特定于供应商的扩展。此类特定于供应商的扩展应具有以下格式之一:

'-' + vendor identifier + '-' + meaningful name 
'_' + vendor identifier + '-' + meaningful name

例子):

例如,如果 XYZ 组织添加了一个属性来描述显示器东侧边框的颜色,他们可能会称之为 -xyz-border-east-color。

其他已知示例:

 -moz-box-sizing
 -moz-border-radius
 -wap-accesskey

任何当前或未来级别的 CSS 都保证永远不会在属性或关键字中使用初始破折号或下划线。因此,典型的 CSS 实现可能无法识别此类属性,并且可能会根据处理解析错误的规则忽略它们。然而,由于初始破折号或下划线是语法的一部分,CSS 2.1 实现者应该始终能够使用符合 CSS 的解析器,无论他们是否支持任何特定于供应商的扩展。

作者应避免特定于供应商的扩展

回答by Gumbo

The complete regular expression is:

完整的正则表达式为:

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

So all of your listed character except “-” and “_” are not allowed if used directly. But you can encode them using a backslash foo\~baror using the unicode notation foo\7E bar.

因此,如果直接使用,则不允许使用除“ -”和“ _”之外的所有列出的字符。但是您可以使用反斜杠foo\~bar或使用 unicode 符号对它们进行编码foo\7E bar

回答by D.Tate

For those looking for a workaround, you can use an attribute selector, for instance, if your class begins with a number. Change:

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

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

to this:

对此:

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

Also, if there are multiple classes, you will need to specify them in selector I think.

另外,如果有多个类,我认为您需要在选择器中指定它们。

Sources:

资料来源:

  1. https://benfrain.com/when-and-where-you-can-use-numbers-in-id-and-class-names/
  2. Is there a workaround to make CSS classes with names that start with numbers valid?
  1. https://benfrain.com/when-and-where-you-can-use-numbers-in-id-and-class-names/
  2. 是否有一种解决方法可以使名称以数字开头的 CSS 类有效?

回答by mofaha

My understanding is that the underscore is technically valid. Check out:

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

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

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

"...errata to the specification published in early 2001 made underscores legal for the first time."

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

The article linked above says never use them, then gives a list of browsers that don't support them, all of which are, in terms of numbers of users at least, long-redundant.

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

回答by Marius

For HTML5/CSS3 classes and IDs can start with numbers.

对于 HTML5/CSS3 类和 ID 可以以数字开头。

回答by Manny Fleurmond

Going off of @Triptych's answer, you can use the following 2 regex matches to make a string valid:

从@Triptych 的回答开始,您可以使用以下 2 个正则表达式匹配来使字符串有效:

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

This is a reverse match that selects anything that isn't a letter, number, dash or underscore for easy removal.

这是一个反向匹配,它选择不是字母、数字、破折号或下划线的任何内容,以便于删除。

^-*[0-9]+

This matches 0 or 1 dashes followed by 1 or more numbers at the beginning of a string, also for easy removal.

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

How I use it in PHP:

我如何在 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 2 or more characters long
return 2 <= strlen($class) ? $class : '';