Images Within Form Fields

May 3rd, 2008
By: Cory Mathews

Adding Background images to your form fields can be easily accomplished with CSS and can add wonders to the look of your forms as well as improve the usability for the user.

Here is what we want to end up accomplishing.
End Result with a red star within the form field

Adding images to your form fields is actually very simple. It works just like adding images to any other item on your page. Here is the CSS for how it is done.

 input {
background:url(img/redStar12.gif) left no-repeat;
padding: 3px 3px 3px 15px;
}

This gives us something like this

End Result with a red star within the form field

View it in action Here

You see that the input class specifies that I want to define this style to all input fields, This includes check boxes, radio buttons ect, with the exception of text areas. So this is a problem.

In my example here I am adding a red star to the input field to specify that the field is required. You notice the padding for the left is at 15 so that the user does not type over the image. This is a great way to indicate a required field.

But there is still the one problem. This is applied to all form input fields. So we need to declare it as a sub class instead. I am going to change the above CSS to solve this problem.

input {
padding: 3px;
}

 input.req {
background:url(img/redStar12.gif) left no-repeat;
padding: 3px 3px 3px 15px;
}

So now you see that I have changed the input class to only add a little padding and a small border and I have added the second piece to only add the image on fields I specify with the class=req.

End Result with a red star within the form field

Here is the final result.

I have seen this technique used on many websites. Some of the more common uses is for required fields like above, for username and password fields. As well as just making the input fields look better.

If you take a look at the search form here on osguide.net it uses this same technique for the search icon.

Enjoy.