Styling search forms
Posted: December 16th, 2007 | Tags: CSS • Tutorials | Posted in: CSS, TutorialsMany people argue against removing browser default styles for form elements, especial replacing the default submit input with an image. This for the simple fact that text in an image cannot be resized by the user.
However, forms are a continual interest for me, and where possible I love to pretty them up:
In this very quick little tutorial I will show you how to style a search form so that it looks just like the one in the image above, but if you can’t be bothered reading, and just want the images and the source there are downloadable as a zip archive. You can also view a live example.
The form markup
Forms generally don’t differ much in terms of markup, and there is very little to them. Here is the markup used for the example:
<form id="form-search" method="post" action="#"> <p> <label for="input-keywords">Search:</label> <input type="text" id="input-keywords" value="" />
<input id="submit-search" type="image" src="img/btn_go.jpg" alt="Search" title="Search" value="submit" /> </p> </form>
One thing I noticed when experimenting with this is the need to remove white space from the text input and the image submit input tags. Otherwise the space is also rendered on the page.
Obviously you will have to add name attributes to provide the application which conducts the search to receive the values of the form’s variables. You may also need to change the method attribute to “get”. Simply look at how the current search form on your site works and take it from there.
The CSS
The first required rule simply zeros margins, adds enough padding to clear the form content from the background image of the little search icon:
#form-search { background: #FFFFFF url(img/icn_search.jpg) no-repeat left center; padding: 0 26px; margin: 0; }
Next we zero margin and padding for the paragraph which contains the form contents:
#form-search p { padding: 0; margin: 0; }
The next rule is important, it uses the “vertical-align” property to neatly line up the form label, text input and submit button, it’s also going to zero out any nasty default margin and padding:
#form-search label, #input-keywords, #submit-search { vertical-align: middle; padding: 0; margin: 0; }
The following rule is simply a matter of taste and adds some typographical alteration to the label text:
#form-search label { font-size: 10px; text-transform: uppercase; }
The final CSS rule applies a fixed height (submit image = 22px height – 1px border on top and bottom) and width to the text input. It also adds a nice border:
#input-keywords { border: 1px solid #7F7F7F; height: 20px; width: 200px; line-height: 20px; }
You will notice that I have also added 20 pixels of line-height to the text inside the input. Adding a line-height value equal to the height defined for the parent effectively centres the text within on the vertical axis.
That’s all there is to it folks, go and make pretty search forms!