Explain Codes LogoExplain Codes Logo

Use Font Awesome Icon in Placeholder

html
responsive-design
css
font-awesome
Nikita BarsukovbyNikita Barsukov·Dec 3, 2024
TLDR

Impress your users by employing a Font Awesome icon within an input placeholder. Layer an icon over an input field using CSS to create this visual treat.

Consider this straightforward example:

<div class="fa-input"> <i class="fa fa-user"></i> <input type="text" placeholder="Username"> </div>
.fa-input { position: relative; /* Ooo! What's this fancy thing? */ } .fa-input .fa { position: absolute; /* Now icon, stay put right there! */ left: 10px; top: 50%; transform: translateY(-50%); /* All aboard the vertical center train! */ } .fa-input input { padding-left: 2em; /* Icon-friendly personal bubble */ }

This CSS positions the Font Awesome icon snugly inside the input field, imitating an icon-laden placeholder.

Using FontAwesome Unicode with CSS

If FontAwesome 4.7 is your cup of tea, remember to refer to the cheatsheet for the corresponding Unicode. Let's see how this pans out:

<input type="text" placeholder="&#xf007; Username" style="font-family: Arial, FontAwesome;">

Voila! The Unicode &#xf007; maps to the user icon, and our font-family configuration ensures we see it displayed just right.

Aesthetic Alterations: CSS and FA (Font Awesome) 5

Are you hitting the streets with FontAwesome 5? CSS' got your back, friend! Try your hand at CSS pseudo-elements:

input[type="text"]::placeholder { font-family: 'FontAwesome 5 Free', 'Arial'; /* CSS Spy Alias */ } input[type="text"]:placeholder-shown { font-family: Arial; /* Back to base, Soldier! */ }

This handy snippet switches to a text font for user input while maintaining the icon for an empty box.

Compatibility pre-checks and SVGs

Before you jump the gun, our old friend browser compatibility test runs are crucial. Test your custom fonts across a plethora of browsers, and input states. I recommend Codewarriors like CodePen or JSFiddle for this.

If FA5 users find pseudo-selectors unnerving or realise they're unsupported, consider using SVG icons instead.

Digging deeper

Deeper CSS customization with less code

For full control over customization, dig into Font Awesome's source code. FA5 Free users will find their treasure in solid.css.

Adding a dynamic touch with jQuery

For a responsive placeholder, intertwine jQuery and font-family:

$('input[type="text"]').on('input', function() { if (this.value) { $(this).addClass('typed'); /* Wow, you typed! Here's a gift: CLASS! */ } else { $(this).removeClass('typed'); /* I'll take that back, thank you. */ } });
input[type="text"].typed { font-family: Arial; /* BACK TO SCHOOL... err... Arial! */ }