Positioning background image on form element with CSS sprites

James Dawson picture James Dawson · Jan 27, 2012 · Viewed 14k times · Source

I am trying to get a magnifying glass as the background for my input element. The magnifying glass icon is part of a CSS sprite that looks like this:

enter image description here

To position it, I've used these properties:

#search-form input[type="text"] {
    background: url('../images/icons.png') no-repeat left center;
    background-position: 0px -30px;
    border: 1px solid #a9e2ff;
    padding: 3px;
    width: 200px;
    font-size: 1em;
    padding-left: 20px;
}

But the background still appears at the top of the input box rather than aligned in the vertical middle and to the left. I've also tried doing:

background: url('../images/icons.png') no-repeat left middle;

but that doesn't work either.

If it matters, although I'm guessing it doesn't, here's my form markup:

<form action="/search" method="get" id="search-form">
    <input type="text" placeholder="Search..." name="s">
</form>

Thanks for any help.

Answer

lorenzo-s picture lorenzo-s · Jan 27, 2012

You declared background-position two times. The first one at the end of the background short-hand property, the second one on the next line. Solution: Split all single background rules like this (additionally, 0 -24px is the correct value):

#search-form input[type="text"] {
    background-image: url('http://i.stack.imgur.com/MFpLm.png');
    background-repeat: no-repeat;
    background-position: 0 -24px;
    border: 1px solid #a9e2ff;
    padding: 3px;
    width: 200px;
    font-size: 1em;
    padding-left: 20px;
}

And now you can face the real problem with your design: other sprites will be visible in the input area if there are no sufficient space between them.