Home / Show an icon in an HTML input using CSS

Show an icon in an HTML input using CSS

Today’s post is a relatively simple tip to add an icon into an HTML text input using CSS so that it sits inside the input box and the text does not appear over it at all.

Working Example

Here’s a working example. It may not work if you are using a feed reader; if not then click through to view this post in a web browser. The icon displayed is from the FamFam icon library but can obviously be whatever you want it to be, including a logo or other type of search icon.


And here it is on the right side.


I personally wouldn’t put it on the right side because people might think they could then click it, whereas this is less likely on the left side. I’ll look at another approach to doing this in a future post where the icon is not a background image and is actually clickable.

How it works

This is a very straight-forward piece of HTML and CSS. Simply set a background image for the input box and add enough padding to the left (or the right) so that the text does not flow over the top of the image.

Here’s the HTML for the text box:

<input type="text" name="whatever" id="funkystyling" />

Here’s the CSS for the image on the left:

#funkystyling {
    background: white url(/path/to/icon.png) left no-repeat;
    padding-left: 17px;
}

And here’s the CSS for the image on the right:

#funkystyling {
    background: white url(/path/to/icon.png) right no-repeat;
    padding-right: 17px;
}

Easy, huh? I’ve set the padding to 17px because the icon is 16px wide, which leaves a little 1px gap between the image and the text. Obviously you need to adjust this based on the width of your icon and far apart you want the text from the icon.