Font Awesome Icons with Pseudo-Elements

Posted on September 09, 2019

Font Awesome’s fifth iteration is huge with the company finally moving to SVG icons from their flagship icon fonts.

With this change, the company has also published packages like react-fontawesome and @fortawesome/fontawesome-svg-core.

This is great for the consumer, because we no longer have to ship the complete icon font. SVG imports with Package managers like Webpack and Parcel ensure that only the icons we use are present in the bundle.

But lots of earlier code would depend on pseudo elements, sort off like this:

<button class="button">Thing</button>
1.button {
2 width: 100%;
3 padding-left: 4rem;
5.button::before {
6 content: '\f7e5';
7 font-family: 'Font-Awesome';

For comparison, here is how you render an SVG icon when rendering with React FontAwesome library and SVG Core:

import ReactDOM from 'react-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCoffee } from '@fortawesome/free-solid-svg-icons';
const element = <FontAwesomeIcon icon={faCoffee} />;
ReactDOM.render(element, document.body);

So, how do we migrate the psuedo element code to the React one? There is no easy answer to that and it involves some markup changes.

First, we have to introduce the icon into the markup.

1import ReactDOM from 'react-dom';
2import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
3import { faCoffee } from '@fortawesome/free-solid-svg-icons';
5function App() {
6 return (
7 <button className="button">
8 <FontAwesomeIcon icon={faCoffee} className="icon" />
9 <span className="button-text">Text</span>
10 </button>
11 );
14ReactDOM.render(<App />, document.body);

Now, you can change the css to:

1.button {
2 width: 100%;
3 padding-left: 4rem;
5.icon {
6 // whatever styles you want the color to take.
7 color: red;

There could be more complicated cases, refer to this PR on BuffetJS to see more cases.

Bonus: How does the SVG change color when you apply color to it’s parent class?

If you inspect the fontawesome SVGs, you will find their path elements have an attribute in common:

<path fill="currentColor" ...></path>

Read more on the trick at CSS Tricks


Buy me a coffeeBuy me a coffee