HOWTO: spruce up your search box with CSS and a background image

Very few designers appreciate the aesthetic of a text input field, and styling form fields cross-browser on any Web site can be a tedious and frustrating experience. The compromise typically involves applying a simple colored border and background to the fields. I think this is the right approach for Web sites and applications that are form field intensive, but the search box plays a special role in the design, and it deserves a little more attention.

Remember, you still want to maintain the general appearance of a text input, since getting wild with the look might contribute to a poor user experience. The following is a measured graphic representing the search box I will be using throughout this tutorial. It has familiar characteristics, but a more pleasant appeal. The lavender only helps to distinguish approximately where the actual input should be placed, and the final background will not contain this color.

A graphic representing a search box.

There are two possible approaches. The entire image can be the background, and a transparent GIF can be positioned over the area representing the submit button, or, the submit graphic can be sliced separately. For this instance, I prefer to slice it separately, since the markup will remain the same irregardless. If the search box and the submit button bleed together, a clickable transparent GIF might be the better option.

XHTML:
<div id="search_box">
    <form id="search_form" method="post" action="/">
        <input type="text" id="s" value="Search" class="swap_value" />
        <input type="image" src="images/btn_search_box.gif" width="27" height="24" id="go" alt="Search" title="Search" />
    </form>
</div>

The div tag with the id attribute of “search_box” will act as the primary container and reference. The form tag is optional in regards to this example, and is coded only to illustrate a real-world scenario. The container will be the exact width and height of the background image. The height could in theory be eliminated from the container, and the submit graphic could help to define the dimensions. However, both the input text field and graphic have float values specified. Without a height (or a hack), the container would then need an element to clear those float values, or else the background will disappear.

For more information on floating and clearing elements, visit Floatutorial by Max Design.

CSS:
#search_box {
    width: 201px;
    height: 31px;
    background: url(images/bg_search_box.gif);
}
#search_box #s {
    float: left;
    padding: 0;
    margin: 6px 0 0 6px;
    border: 0;
    width: 159px;
    background: none;
}
#search_box #go {
    float: right;
    margin: 3px 4px 0 0;
}

The margins on the text input and the image input help to position the elements appropriately after applying the float properties. For the text input, all the default browser property values are overridden, which gives the illusion that the background is actually the text input. The width should be defined in pixels, and the size attribute should be left off the text input tag in the XHTML.

You might be tempted to give the text input a height, but you should avoid this practice. If a user increases the font size via the browser, you want the input to accommodate the new size. It may overflow the container and the background, but in most circumstances this is okay. The initial visual effect is worth the sacrifice for the very small number of users who will need (and know how) to resize the font.

11/04/07 Update:
There is a complication in Safari v.2.0. The text box still shows a border, even though the border width is zero. This problem does not appear in Webkit, or Safari v.3.0 for the PC. A common fix is much like the one in use on Ajaxian.com or Apple.com, which uses JavaScript to apply a class for Safari.

Click here to view the finished search box.

Leave a Comment

Comments are moderated. No profanity. Only <a>...</a>, <blockquote>...</blockquote>, and <code>...</code> are allowed.

Seperate paragraphs by pressing the "Enter" key twice, or press it once to break to a new line.

63 Comments

#01, Aug 15 2007

glen

Hey thats really tidy, thanks for sharing

G

#02, Aug 15 2007

Brian

Hi Glen,

I’m happy you liked it - thanks for the comment.

Brian

#03, Aug 15 2007

Stefan Hayden

wow… yeah… that seemed alot easier then I thought it would be. Does that work in all browsers?

I see it works in FF2 and IE7. what browsers does this break in? Has anyone tested that?

#04, Aug 15 2007

plop

Tried it on Opera?

#05, Aug 15 2007

Brian

For those Opera users I apologize — I forgot to “zero-out” the margin on the form tag. This is fixed and has been tested in version 9.22. Enjoy!

#06, Aug 15 2007

Tims Blog » Blog Archive » Patches and Add-ons

[…] howto spruce up your search box with css and a background image […]

#07, Aug 15 2007

Matthew

Exactly what ive been looking for, took me ages to find this page, thankyou, i like your search bar on your site, very nice.

#08, Aug 15 2007

Brian

Hey Matthew,

Happy I could help out - I like the design of your site. Very clean.

Brian

#09, Aug 15 2007

links for 2007-08-15 : Christopher Schmitt

[…] Spruce Up Your Search Box with CSS and a Background Image “Very few designers appreciate the aesthetic of a text input field…” (tags: css webdesign search design javascript input Programming howto reference style tutorials tips web development form) […]

#10, Aug 15 2007

links for 2007-08-16 « Simply… A User

[…] HOWTO: spruce up your search box with CSS and a background image » d’bug (tags: background css webdesign search javascript design input programming html reference **) […]

#11, Aug 15 2007

links for 2007-08-16 « My Journal of Life

[…] HOWTO: spruce up your search box with CSS and a background image » d’bug (tags: css web search) […]

#12, Aug 16 2007

links for 2007-08-16 « toonz

[…] HOWTO: spruce up your search box with CSS and a background image » d’bug (tags: css javascript input) […]

#13, Aug 16 2007

Fatih HayrioÄŸlu’nun not defteri » 17 AÄŸustos 2007 Web’den Seçme Haberler

[…] CSS ile zemin resimli arama alanları yapmayı anlatan güzel bir makale. Link […]

#15, Aug 17 2007

Colocar imagem de fundo em input text com CSS

[…] Este artigo que estamos indicando lhe ensinará a colocar uma imagem de fundo (background) em um campo input text do seu formulário utilizando CSS. Neste artigo o exemplo abordado é um campo de busca com bordas arredondadas como a do exemplo acima. A mesma técnica pode ser utilizada para personalizar todos os campos de um formulário. Veja o exemplo funcionando. Para mais detalhes visite: blog.reindel.com […]

#16, Aug 18 2007

links for 2007-08-19 | giancarlo.dimassa.net

[…] HOWTO: spruce up your search box with CSS and a background image » d’bug (tags: css webdesign search design javascript input forms programming button code control development form box background) […]

#17, Aug 19 2007

links for 2007-08-19

[…] HOWTO: spruce up your search box with CSS and a background image » d’bug mais uma css (tags: css) […]

#18, Aug 19 2007

eburhan.com » Css ile zarif arama kutuları hazırlamak

[…] Referans: http://blog.reindel.com/…with-css-and-a-background-image Benzer Yazılar Free CSS Toolbox: Css kodlayanların alet kutusu Acaba bu web sitesi neyle yapılmış? Paste2: yeni nesil kod panosu Aradığınız web sitesine ÅŸu anda ulaşılamıyor mu? jQuery dünyasına adım atıyoruz […]

#19, Aug 20 2007

Scripts Directory

Very nice example of creating a search box with CSS! I like it very much.

#20, Aug 23 2007

michelle

this is great, i never thought of setting the background on the containing div (i’m working on some code where i set the background on the input field). i like your method instead. i’ll be bookmarking your site for more tips!

#21, Aug 23 2007

Brian

Hey Michelle,

Great to hear! Be sure to subscribe to the feed for updates :)

Brian

#23, Sep 01 2007

Naser

Thanks a lot for this awesome tip, Brian :) I’m too broke to afford a custom domain name and subsequently a custom wordpress installation. So I do all my blogging in blogger. I applied your CSS hacks to my blogger-blog and they worked flawlessly. Take a look at it over here: http://atunu.blogspot.com . I had to make some changes to the actual XHTML to suite my site’s syntax.

Sorry for stealing the image you used for the example though :( I had to go through quite a trouble to dig them up from the source of this post..but human intuition always dictates. If you have any problem with me using the images, just leave me a comment or mail me and I will replace them with whatever I can cook up with Photoshop.

#24, Sep 01 2007

Brian

Great job Naser — it looks good! You are free to use those graphics as you see fit — so no worries. I designed it for the example, but it is available for anyone to use on their own site.

#25, Oct 03 2007

Med

Super slice of CSS thank you!

#26, Oct 05 2007

Ken

Does not work in Safari.

#27, Oct 12 2007

Brian

Hi Ken,

Sorry for the long delay in approving your comment. I wanted to check this out, but I have not had the time. Do you have a version of Safari that you were using, or, is anyone else having trouble getting this to work in Safari? Also, what was the issue that you were experiencing? Thanks.

#28, Oct 12 2007

Blogulate

How do u make the “search” text disappear and the appear again on focuslost ?

#29, Oct 14 2007

Kim

In Safari a square input box is positioned in front of the image.

#30, Oct 14 2007

Brian

I do not have Safari on a Mac, but on the PC it looks okay. I will try and have a look on a Mac to find a fix.

@Blogulate

I use jQuery/JavaScript to accomplish this. The script is in the source of the example.

#31, Oct 17 2007

.ink.

Brian, I’m truly behind the coding curve and a day searching before finding to come upon your site. Like a thirsty man finding water in the desert, I am grateful.

I used the listed code, and it doesn’t work. I’m short on time, so will try it again later.

But what I’d really like to know is can this code produce a result like the serach field on http://www.ejeliot.com/blog/59?

I use a dark background, and would like to keep the search cell dark as well. It is infinitely more aesthetic - and doesn’t look like someone dropped square white paint on the screen.

#32, Oct 17 2007

Brian

@.ink.

It sure can produce those results - almost anything you can think up :)

I am currently researching a Safari fix though. However, in other browsers you shouldn’t have difficulty. Let me know what problems you are facing.

#33, Oct 17 2007

.ink.

Brian, thank you for post. I placed search box code below my sidebars .. the search box picked up the color. Good start.

But, testing it, I get an error code:
Method Not Allowed
Error 405

My assumption is, Mia Culpa, and clueless how and why. I see Naser is using Blogspot and had no problems.

Any recommendation?

#34, Oct 17 2007

Brian

I am getting an error in this function on your site:

function togglecomments (postid) {
varwhichpost:document.getElementById(postid);
ifwhichpostclassname:=”
whichpostclassname:”
}

else {
whichpostclassname:”
}

Also, I see for #search_box that you have no URL specified for the background:

#search_box {
width: 201px;
height: 31px;
background: url( );
}

For the solution you are looking for, I might just suggest styling the input instead.

HTML:

<input type=”text” id=”search_box” />

CSS:

#search_box {
border: 1px solid #fff;
background: #000;
}

#35, Oct 19 2007

.ink.

Brian, Thank you for helping. I discovered the search function drops into Google’s lap, and want search results in the Blog.

#36, Oct 21 2007

Dmitry

Hey,
This code broke for me in FF2 when i added a name attribute to input tag like :

I am using php code to extract post values so my inputs have to be named. This code works for IE but not FF does any one have any ideas or workarounds. thanks
_D

#37, Oct 22 2007

Brian

Hi Dmitry,

Looks like the code got stripped from the comment, but the name tag shouldn’t affect the visual display of the input. Some other element may be conflicting with it. Could you send me some code by email that I could look at?

#38, Nov 11 2007

Slob Jones

This thing checked out great for me until I plugged in the form fields for my search engine.

Unfortunately, now the form does not display properly in IE.

Instead, only in IE, it pushes the search field down one line for each form field. So, the search form appears four or five lines down the page.

Any way I can prevent this from happening?

#39, Nov 12 2007

Brian

Hey Slob,

I’m not sure if this is it, but try putting this in your style sheet:

form {
margin: 0;
}

#41, Dec 11 2007

Myles

Hi Brian,

Great custom search implementation.
I have it running on www.pixelshell.com however have noticed that the search box input is misaligned in Safari v3
In FF plays nice, for IEs I had to adjust padding with conditional comments but am surprised with Safari as normally it is the same as FF.
Clearly I have bodged something up since your example is aligned correctly in Safari.
Any thoughts what I have done?

Thanks :)

#42, Dec 14 2007

Brian

Hi Myles,

If this is Safari on the Mac, then you might have some difficulties getting it to work correctly without JavaScript. If it is Safari on the PC, then it should be okay. You could try removing the “fieldset” tag, or making sure that your form has a margin of zero. Either one of those might be causing conflicts.

Hope that helps!

Brian

#43, Jan 16 2008

Elizabeth

Really nice!

I noticed the text entry and submit button alignment are off in Opera, but I’m hoping to find a solution for that. If you have any, please let me know. Otherwise, nice work!

#44, Jan 17 2008

Brian

Hi Elizabeth,

I think this is because you need to set the following style in your stylesheet:

form {
margin: 0;
}

#45, Feb 29 2008

Rory Reiff

Hello:

This seems to work fine for me so far as stated in your article, with the exception that only in firefox when you put in text into the search field, and then reload the page, the original value is not reloaded, but the text you entered. Please help!

#46, Mar 01 2008

Brian

Hi Rory,

If I’m not mistaken, this is actually a FF “feature” that no other browser implements. Typically, if a user refreshes the page, they actually want the values to be reset. If you really wanted this functionality back, then you would have to remove the JavaScript attached to the form field. I hope this helps.

#47, Mar 02 2008

stevehuynh

Thanks very nice - i am trying to set up using your tutorial at http://ilovephim.com/phim/

It need to have the search box that stand out and pretty!

thanks again,
STeve

#48, Mar 03 2008

Rory Reiff

Thanks Brian.

I added the following code into the javascript which forces FF to reload the “value”:

$(’#s’).val(’Search by google’);

My one remaining question before I implement this new search box on our site…it does not work on IE 5. I know this is an outdated browser, but it is being used to navigate to our site.

Here is the url: www.pitzer.edu/search/results/

Any ideas why its not working on IE5? Thanks for the help…this site has been wonderful!

#49, Mar 04 2008

lchlebda

It doesn’t work in IE 6.0

#50, Mar 04 2008

Brian

@Rory

I would drop your support for IE 5 and IE 5.5, and then let it degrade. I know as an educational institution it can be hard to let go of users who are on these browsers, but it is a necessary part of the development process. Honestly, I did not test it in anything other than A-grade browsers. Sorry I can’t be of more help in that area.

@lchlebda

I am able to view it in IE6, and currently do not have any issues. I am trying to fix an issue with this site in IE6, but it should not affect the tutorial.

#51, Mar 09 2008

Matt

Could you remove the blur border with something like -

input { outline: none; }

#52, Mar 16 2008

Text / Search Box: Using Background Images | David Bisset: Web Designer, Coder, Wordpress Guru

[…] there appears to be a minor issue in Safari 2, this method of howto “spruce up your search box with CSS and a background image” worked well for me in a recent project. Tags: […]

#53, Mar 31 2008

Ramesh Rasaiyan

Hi,

This example looks simple but very powerful. I liked it very much.

Thanks for sharing.

Ramesh Rasaiyan

#55, May 09 2008

Jason King

Thanks!

I followed your advice and now have a good-looking search box on my new Greek Care website.

That’s working great in IE7 and Firefox.

#56, May 13 2008

Luc

I know this is an old post but I just found it and it’s great! As the first comment mentioned, it’s really tidy.

Thanks for posting the information - it’s really useful!

#57, May 20 2008

Darryl

Very slick search box! However, it doesn’t validate using a strict doc type (there are 5 errors on your example page). If possible could you fix your code so it validates ?

#58, May 28 2008

Sarah

I liked this quick tutorial alot. It has been submitted to designbump.com here (incase you want to vote it up) so that others can see it. Thanks again!

Sarah

#59, May 31 2008

John Campbell

Great tutorial! I submitted it to designbump.com, you can vote it up here.

Keep up the good work!

- John

#60, Jun 10 2008

Shaun

This is really an awesome tip, thanks for sharing. I can’t seem to make it display correctly in IE7, I personally don’t even care, but the site listed as my URL is being built for a client and I’d like to try and fix it. Any ideas about issues with IE? Thanks again for sharing this, it really helped me out!

#61, Jun 12 2008

video bulur

cool search bar, i will try it now
thanks…

#62, Jun 18 2008

Michael

I love the look of your site.

Your site came up first for “search box field” in Google. Thanks for the tip. I’m trying to incorporate a search box field into a logo of mine.

#63, Jun 24 2008

bruce

Great work! But it is so big script :( Only for “search form” I need NOT whole Pack. Jquery-pack more then 21Kb. Trivial content-pages are lesser then this script!