Use Font Awesome Icons in CSS

L84 picture L84 · Feb 6, 2013 · Viewed 555k times · Source

I have some CSS that looks like this:

#content h2 {
   background: url(../images/tContent.jpg) no-repeat 0 6px;
}

I would like to replace the image with an icon from Font Awesome.

I do not see anyway to use the icon in CSS as a background image. Is this possible to do assuming the Font Awesome stylesheets/fonts are loaded before my CSS?

Answer

You can't use text as a background image, but you can use the :before or :after pseudo classes to place a text character where you want it, without having to add all kinds of messy extra mark-up.

Be sure to set position:relative on your actual text wrapper for the positioning to work.

.mytextwithicon {
    position:relative;
}    
.mytextwithicon:before {
    content: "\25AE";  /* this is your text. You can also use UTF-8 character codes as I do here */
    font-family: FontAwesome;
    left:-5px;
    position:absolute;
    top:0;
 }

EDIT:

Font Awesome v5 uses other font names than older versions:

  • For FontAwesome v5, Free Version, use: font-family: "Font Awesome 5 Free"
  • For FontAwesome v5, Pro Version, use: font-family: "Font Awesome 5 Pro"

Note that you should set the same font-weight property, too (seems to be 900).

Another way to find the font name is to right click on a sample font awesome icon on your page and get the font name (same way the utf-8 icon code can be found, but note that you can find it out on :before).