Search code examples
htmlcssescapinghtml-escape-characters

Is it possible to use the space character in CSS class names?


I have a case with computer-generated class names where it could be that the class name might contain a space character (I don't have direct control over the IDs that are turned into class names). I figured out how to escape all characters in CSS (see the excellent answers in Which characters are valid in CSS class names/selectors? and http://mathiasbynens.be/notes/css-escapes).

But I didn't manage to get a space character escaped in a CSS class name in the HTML code.

I now used a solution that avoids spaces, but I'm curious nevertheless if / how it would be possible to escape the space character in the class attribute value.

E.g.: my class name is "a b".

I can write a CSS selector in CSS as .a\20 b { }.

But using &#x20; in the attribute such as <div class="a&#x20;b"/> will be interpreted the same as <div class="a b"/> and this defines two classes.


Solution

  • 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.

    Of course it’s possible to escape a space character, e.g. &#x20; — HTML attribute values can contain character references per 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.

    However, it doesn’t matter whether the space is HTML-escaped or not for the above statement to apply. A HTML-encoded space character still decodes to a space character, and so e.g. class="a&#x20;b" still results in “a set of space-separated tokens”. See e.g. https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(double-quoted)-state for how double-quoted attribute values are parsed.