我遇到过计算机生成类名的情况,其中类名可能包含空格字符(我无法直接控制转换为类名的 ID)。 我想出了如何转义 CSS 中的所有字符(请参阅 Which characters are valid in CSS class names/selectors? 和 http://mathiasbynens.be/notes/css-escapes 中的优秀答案)。
但我没能在 HTML 代码的 CSS 类名中转义空格字符。
我现在使用了一个避免空格的解决方案,但我还是很好奇是否/如何转义类属性值中的空格字符。
例如:我的类(class)名称是"a b"
.
我可以在 CSS 中编写一个 CSS 选择器作为 .a\20 b { }
.
但使用  
在 <div class="a b"/>
等属性中将被解释为与 <div class="a b"/>
相同这定义了两个类。
最佳答案
https://html.spec.whatwg.org/multipage/dom.html#classes
When specified on HTML elements, the
class
attribute must have a value that is a set of space-separated tokens representing the various classes that the element belongs to.
当然可以转义空格字符,例如
— HTML 属性值可以包含每个 https://html.spec.whatwg.org/multipage/syntax.html#syntax-attribute-value 的字符引用:
Attribute values are a mixture of text and character references, except with the additional restriction that the text cannot contain an ambiguous ampersand.
然而,空格是否被 HTML 转义并不重要,因为上面的语句适用。 HTML 编码的空格字符仍会解码为空格字符,例如class="a b"
仍然会产生“一组以空格分隔的标记”。参见例如https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(double-quoted)-state了解如何解析双引号属性值。
关于html - 是否可以在 CSS 类名中使用空格字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50812118/