Using attr(data-icon) property to display unicode before element
CSS escape sequences only work within CSS strings. When you take a CSS escape sequence from an HTML attribute (i.e. outside of CSS), it will be read literally, not interpreted as part of a CSS string.
If you want to encode the character within an HTML attribute, you need to encode it as an HTML entity. This will be seen by CSS as the corresponding Unicode character. Since this is a hexadecimal escape sequence you can transliterate it like so:
<div data-icon="▶">Title</div>
Alternatively you can just use the Unicode character itself:
<div data-icon="▶">Title</div>
If the attribute's value needs to be reactive in Vue or any of the now popular JavaScript frameworks, use the JavaScript escape sequence notation, within a JavaScript string (if you're confused, just pay attention to the nested quotes in the following example):
<div :data-icon="'\u25b6'">Title</div>
Related videos on Youtube
OutOfSpaceHoneyBadger
Updated on June 02, 2022Comments
-
OutOfSpaceHoneyBadger almost 2 years
Lets demonstrate an example with simple HTML code like this:
<div data-icon="\25B6">Title</div>
I would like this element to have an prefix icon set by it's data attribute (data-icon) so I set CSS file like this:
div:before { content: attr(data-icon); }
My desired output of this example would look like this:
▶Title
Instead of desired output all I can get is this:
\25B6Title
So my question is: what am I doing wrong / what am I missing?
JSFiddle example: http://jsfiddle.net/Lqgr9zv6/
-
OutOfSpaceHoneyBadger about 9 yearsTo your alternative answer: if I work in a code with only an unicode ("\25B6" in this case), can I transfer it to "▶"? So I can then set data-attribute later?
-
OutOfSpaceHoneyBadger about 9 yearsYes you can, but triangle in this case was just an example. Instead of this triangle can be used pretty much every icon. On the other hand - yes - this is way to get the desired output :-)
-
BoltClock about 9 years@HoneyBadgerJunior: I'm not sure what you mean, could you clarify?
-
OutOfSpaceHoneyBadger about 9 yearsI set my data-attribute with JS and all I can work with is unicode. What I meant was: can I transform unicode into a concrete character purely in JavaScript? And then set this character into a data-attribute like you pointer out in your alternative solution. Hope I made my point more understandable :-)
-
BoltClock about 9 years@HoneyBadgerJunior: Yes, you should be able to. How you do that is a separate question entirely, but yes, it's possible :)
-
kaplan over 4 yearsthat note about reactive is very helpful. It also works for Private Use if you make your own fonts that have icons assigned to private use.
<span aria-hidden="true" :data-icon="'\ue041'"></span>
works with same csscontent: attr(data-icon);