Sometimes you want to display an icon in your website somewhere, but you do not want to touch the HTML. For instance if you have an auto-generated link in your CMS and you want to prefix it with an icon. This is actually very easy to do, because that is exactly what icon font vendors like Bootstrap Glyphicons and FontAwesome already do!
Most of the times they let you add icons with an HTML tag like this:
This is how you would add a rocket icon in font-awesome. As you can see it is an ‘i’ element with two classes. The element type does not really matter, but the classes do. The first class ‘fa’ adds the base style rules for adding an icon. If we check out the FontAwesome GitHub project:
As you can see it sets up the element for being inline with text elements, the font-size being 14px, some rendering settings and most important: the font-family being ‘FontAwesome’. This is what makes the icon appear if we add a certain character code. So how does it add the character code? Let’s check out the ‘fa-rocket’ class:
As you can see, it adds the character ‘\f135’ before the content of the ‘i’ element. Because the element is (should be) empty, it will only contain ‘\f135’ which is a rocket icon in the FontAwesome font.
So how can we take advantage of this knowledge? Let’s say we want to display a globe icon before a link of class ‘web-link’. As we are using SASS we will start making a mixin:
You can use vanilla CSS to add the style rules to certain classes directly, but SASS makes this way more flexible.
I have stripped some of the default styles, because they are not necessary and you might want to use your own spacing/sizing. Now we create a variable for the icon(s) we want to use and use them in our ‘web-link’ class:
We have now created a usable icon insertion method in our own webpage. Now render the element in our HTML and we should get something like the result below.
FontAwesome already provides you with a FontAwesome SASS project, containing all the icons and mixins like we just created. But we have now learned how this works and can create our own mixins, suiting our needs and using other icon sets. For instance Bootstrap Glyphicons will work almost the same except for other character codes and using the ‘Glyphicon Halflings’ font instead of ‘FontAwesome’.
You can either get the character codes for the icons by digging into the source code of the icon sets, inspecting the icons with your browser or looking at various cheatsheets like this one for FontAwesome.
I hope that by now you understand how icon font insertion works and are able to take advantage of this for your own projects! For instance I have used it for the blockquotes with the ‘light bulb’ icons in this post. Happy coding!
- Font Awesome fortawesome.github.io/Font-Awesome/