html - 是否可以在 CSS 类名中使用空格字符?

标签 html css escaping html-escape-characters

我遇到过计算机生成类名的情况,其中类名可能包含空格字符(我无法直接控制转换为类名的 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 { } .

但使用 &#x20;<div class="a&#x20;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/

相关文章:

JavaScript 获取多个已知元素 ID

javascript - 通过javascript获取网页元素节点的文本节点

php - 这段代码中的 "mysql_real_escape_string"应该放在哪里?

c# - WPF 和字符串格式化

html - 在不使用绝对的情况下在窗口调整大小时向上移动 div

javascript - 第 n 个类型元素的 css 选择器 - nth-of-type() 的奇怪实现

css - 如何在 Css 字体系列中使用 "Wedding text "?

php - 如何在 PHP 中转义输出

javascript - elem.innerHTML 仅在设置超时后可用

html - "inline-block"div 之间的神秘空白