Skip to content Skip to sidebar Skip to footer

Use Fontawesome Icon Inside A ::before Pseudo Element With Attr()

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

Solution 1:

Try with Unicode

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.

you should add "&#x" before your font-Awesome icon code. ie, if you want to use /f086, then write &#xf086 instead

get the unicode from here - https://fortawesome.github.io/Font-Awesome/cheatsheet/

UPDATE

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

div:before {
  content: attr(data-background-icon);
  font-family: "FontAwesome";
}
<linkhref="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" /><divdata-background-icon='&#xf086;'></div>

Solution 2:

CSS reads \f086 as a string and not as an escape sequence. The fix is either to use it directly inside content attribute like content: '\f086'; or directly copying and pasting icon in HTML attribute (make sure you save your file as UTF-8)

HTML:

<divdata-background-icon=""></div><!-- this is the bluetooth icon copied from fontawesome -->

CSS:

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

OR make use of HTML entities:

HTML:

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

CSS:

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

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

Post a Comment for "Use Fontawesome Icon Inside A ::before Pseudo Element With Attr()"