Deka87 Deka87 - 6 months ago 15
HTML Question

Use font awesome icon as css content

I want to use a font awesome icon as a css content, i.e.

a:before {
content: "<i class='fa...'>...</i>";
}


I know I cannot use html code in
content
, so is it only images left?

Answer

That's the wrong way to use it, open the font awesome stylesheet, go to the class of the font you want to use say fa-phone and then copy the content property under that class with the entity and than use it like

a:before {
   font-family: FontAwesome;
   content: "\f095";
}

Demo

Just make sure that if you are looking to target a specific a tag, than consider using a class instead to make it more specific like

a.class_name:before { 
    font-family: FontAwesome;
    content: "\f095";
}

Using the way above will stick the icon with the remaining text of yours, so if you want to have a bit of space between the two of the, make it display: inline-block; and use some padding-right

a:before {
   font-family: FontAwesome;
   content: "\f095";
   display: inline-block;
   padding-right: 3px;
   vertical-align: middle;
}

Extending this answer further, since many might be having a requirement to change an icon on hover, so for that, we can write a separate selector and rules for :hover action

a:hover:before {
 content: "\f099"; /* code of the icon you want to change on hover */
}

Demo

Now in the above example, icon nudges because of the different size and you surely don't want that, so you can set a fixed width on the base declaration like

a:before {
   /* Other properties here, look in the above code snippets */
   width: 12px; /* add some desired width here to prevent nudge */ 
}

Demo

Comments