Html special characters in css content using attr ()

Relevant code: http://codepen.io/anon/pen/ocptF/

EDIT: codepen uses Jade, and thus a few things are sorted out. I didn't know about this when I started this question. Basically, I thought the CSS attr () would copy over the HTML attribute literally, but it doesn't.

I would like to use a CSS feature attr

to fill content

for some pseudo-elements. However, it prints 004

if the HTML attribute is set to \f004

and 08fa

when \f08fa

.

Relevant lines:

HTML:

<div class="zoomfade" data-fill='\f004' data-unfill='\f08a'></div>

      

CSS

.zoomfade:before {
  content: attr(data-unfill);
  position: absolute;
}

.zoomfade:before {
  content: attr(data-fill);
  position: absolute;
}

      

Thank!

+2


source to share


1 answer


CSS escape scripts are handled specifically in CSS syntax. When you specify it in an HTML attribute value, use that value in CSS attr()

, it is taken literally. From the CSS2.1 spec :

attr (X)
This function returns the value of the X attribute for the selector object as a string. The string is not processed by the CSS processor. [...]

Because you specify character codes in HTML attribute values, you can either use HTML character references, entity references, or Unicode characters. It's worth noting that the two character codes you have are apparently not valid, so they might not work at all.

EDIT: [...] Basically I thought the CSS attr () would copy over the HTML attribute literally, but it doesn't.



It copies the attribute value according to the DOM, which may be different from how it appears in the source, for example. the original markup or script that generates the element.

For example, if the source is in raw HTML markup, then, as I mentioned above, you will need to use the HTML character escapes because the HTML is parsed by the HTML parser. If the elements are generated using a JS template like Jade, then the escape character will take the form \u

followed by hexadecimal codes. In both cases, the corresponding parsers will translate the escape sequences into their representative characters, and the characters themselves are what is stored in the DOM as part of the attribute value.

Of course, again there is always an alternative to just use Unicode characters. If your source files are encoded as UTF-8, then you should have no problem using characters directly.

+4


source







All Articles