Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using attr(data-icon) property to display unicode before element

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/

like image 710
OutOfSpaceHoneyBadger Avatar asked May 07 '15 10:05

OutOfSpaceHoneyBadger


People also ask

What is attr() in CSS?

The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.

Can you set attributes with CSS?

Styling with data attributesCSS can select HTML elements based on attributes and their values.

How to get data attribute in CSS?

Getting a data attribute's value in CSS # You can access the content of a data attribute with the attr() CSS function. In every major browser, it's use is limited to the content property. For example, let's say you wanted to add some content dynamically to a component based on a data attribute value. You could do this.

What is data icon in HTML?

data-icon is a new alternative approach that uses the HTML5 data- attribute in combination with CSS attribute selectors. This new attribute lets us add our own metadata to elements, as long as its prefixed by data- and doesn't contain any uppercase letters.


1 Answers

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="&#x25B6;">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>
like image 73
BoltClock Avatar answered Sep 28 '22 06:09

BoltClock