Explain Codes LogoExplain Codes Logo

Use Font Awesome Icon as CSS Content

html
responsive-design
css
font-awesome
Alex KataevbyAlex Kataev·Nov 14, 2024
TLDR

Inject Font Awesome icons into your HTML layouts using CSS pseudo-elements ::before or ::after, by giving them the right font-family, font-weight, and assigning the icon's Unicode to content. For instance:

For a solid camera icon:

.icon::before { font-family: 'Font Awesome 5 Free'; /* They made the font, we make it awesome. */ font-weight: 900; /* "Solid" icons need more "weight" in life, give 'em 900. */ content: "\f030"; /* Say cheese...or in Unicode "\f030". */ }

And in your HTML:

<div class="icon"></div>

Note: Feel free change the Unicode \f030 to the icon you want. You can find these in the Font Awesome cheatsheet.

Handling interactions

To make your icons interactive, for instance, changing when hovered over, add a specific hover selector:

.icon:hover::before { content: "\f08b"; /* Ever seen an icon change on hover? Now you have. */ }

Position and space

To properly align and space your icons, set the icons' display to inline-block and define the padding and width:

.icon::before { display: inline-block; padding-right: 4px; /* Room to breathe. Adjust as needed. */ width: 1em; /* Because Consistency is king! */ }

Sans "<i>" and working with SCSS

Say farewell to <i> tags for icons, and embrace cleaner markup with CSS classes. And if you're more into SCSS, handling Font Awesome icons is simpler:

.icon::before { @include fa-icon; content: fa-content($fa-var-camera); }

In your HTML, just use:

<div class="icon"></div>

Going the extra mile with icons

Solid or regular? Pick your style

Using the font-weight property, customize the style of Font Awesome icons. Want regular icons? Go for 400. Prefer them solid? 900 it is.

Keep icons from nudging

To keep your icons in line when content changes, apply a fixed width:

.icon::before { width: 1.5em; /* Keep 'em steady! */ }

Dialing up your CSS game

Responsive icon sizing

Want your icons to adapt to font size changes seamlessly? Here's how you do it:

.icon::before { font-size: inherit; /* When in Rome... */ }

Accessible Icons

Making your layout enjoyable for everyone, even for screen reader users, is important:

.icon::before { aria-hidden: "true"; }

Splash of color

Dress up your icons by assigning them fit-for-design colors:

.icon::before { color: #f0ad4e; /* Mix, match, or go wild but keep it classy! */ }

Vertical alignment

Avoid misalignment of icons with text. Use the vertical-align property to keep everything in check:

.icon::before { vertical-align: middle; /* This is called keeping a balanced diet of pixels. */ }