1

I want to assign an icon from an iconfont to a span element with a before pseudo element. The value of the icon is dynamically written to the HTML as data attribute.

Unfortunately, in the following example, the HTML does not show the icon, but "\EA46". Probably it is because of the backslash. Does anyone have an idea how I could solve this?

.testicon {
  font-family: iconFont;
}

[data-icon]:before {
  content: attr(data-icon);
}
<span class="testicon" data-icon="\EA46"></span>
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
rhodes
  • 169
  • 1
  • 11

2 Answers2

0

I cannot work out how to do this using just a data-icon attribute, but combined with setting a CSS variable style in the element this works. Note the quotes are necessary.

(Example uses Fontawesome and the hex coded character for a bug so it can be seen as other than a blank square because the given hex code isn't a character in FA)

<!DOCTYPE html>
<html>
<head>
<title>Test icon as data attribute bug?</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
.testicon {
   font-family: fontAwesome, monospace;
}

[data-icon]:before {
   content: var(--icon);
}
</style>
</head>
<body>

<span class="testicon" style="--icon: '\f188';" data-icon></span>

</body>
</html>
A Haworth
  • 30,908
  • 4
  • 11
  • 14
0

CSS and HTML have different methods to encode/escape unicode characters. You trying to use the CSS method in a HTML context, which won't work (a backslash is not a "special" character in HTML).

You need to use the HTML method: a character reference (or use the literal character, but that isn't really readable).

.testicon {
  font-family: iconFont;
}

[data-icon]:before {
  content: attr(data-icon);
}
<span class="testicon" data-icon="&#xEA46;"></span>
<span class="testicon" data-icon=""></span>
RoToRa
  • 37,635
  • 12
  • 69
  • 105