Put icon inside input element in a form
Get rolling and embed an icon inside an input with the help of CSS. Pick an icon font, a sibling like Font Awesome, within a position: relative; wrapper, set the icon to position: absolute;. Tune the icon's top and left properties for a cracking alignment:
This keeps the search icon sailing smooth, vertically centered, and a bit of padding infused to the input to prevent Hitchcock's "The Birds" scenario with text-icon overlap.
Configure icons with CSS backgrounds
Here, being an artist pays off. Use the mighty background-image
CSS property to paint your input field. Suitable when icon integration as part of the input style is your jam:
To incorporate this in your form:
For the iconsizer, apply background-size
to make it homely within the input and set background-repeat
to no-repeat
.
Click event handlers: Icons in Action
Icons can be more than eye-candy. When interacted, like clicking on them, they may perform specific actions. Wrap both icon and control within a label
or div
, let JavaScript handle the actions:
Cross-browser compatibility tricks
Browser diversity is an age-old reality. Confirm that your masterpiece works across all browsers. Modern browsers are good with prior techniques, but for the older relics, encapsulate the icon and input within a div
with a border. It's like a time machine going back to offer support for legacy wonders!
Advanced use-cases
Interactive icon: From basic to dynamic
An input can go live responding to user keystrokes. A nifty scenario: revealing an X to clear the input once it's populated:
Designing emotion: Icon for validation feedback
Icons can wear an emotion reflecting user input validation: a tick for success or an exclamation for error. It makes forms more alive, interactive, and user-friendly.
Pro-Tip: Make it accessible
Ensure accessibility is on point. Provide alt text if your icon relays critical info, or use aria-label on the input for our friends at the screen readers.
Was this article helpful?