Use the FontAwesome icon inside the :: element before the pseudo-element with attr ()

I am trying to insert a FontAwesome icon inside the ::before pseudo-element with attr() . The source code is more complex, however this will give you an idea of ​​what I want:

 <div data-background-icon="\f086"></div> div::before { content: attr(data-background-icon); font-family: "FontAwesome"; } 

https://jsfiddle.net/grutcop8/

This does not work, while the usual way to embed it works fine:

 div::before { content: "\f086"; font-family: "FontAwesome"; } 

Anything I miss?

+10
source share
2 answers

Try with Unicode

CSS escape sequences only work inside CSS strings. When you take a CSS escape sequence from an HTML attribute (i.e. outside CSS), it will be read literally, and not interpreted as part of the CSS string.

If you want to encode a character in an HTML attribute, you need to encode it as an HTML entity.

You must add "&#x" in front of your Awesome font icon. that is, if you want to use /f086 , write

get unicode from here - https://fortawesome.imtqy.com/Font-Awesome/cheatsheet/

UPDATE

If you are using fontAwesome 5, change the font-family: "FontAwesome"; to font-family: 'Font Awesome 5 Free';

 div:before { content: attr(data-background-icon); font-family: "FontAwesome"; } 
 <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/> <div data-background-icon='&#xf086;'></div> 
+17
source

CSS reads \f086 as a string, not as an escape sequence. The fix is ​​to use it directly inside the content attribute, for example content: '\f086'; , or directly copy and paste the icon into the HTML attribute (make sure you save the file as UTF-8)

HTML:

 <div data-background-icon="οŠ”"></div> <!-- this is the bluetooth icon copied from fontawesome --> 

CSS

 div::before { content: attr(data-background-icon); font-family: "FontAwesome"; } 

OR use HTML objects:

HTML:

 <div data-background-icon="&#xf086;"></div> 

CSS

 div::before { content: attr(data-background-icon); font-family: "FontAwesome"; } 

Fiddle: https://jsfiddle.net/76v9e2ur/1/

+1
source

All Articles