Styling a search form with CSS

Search forms can be easily stylized with CSS without much effort. The only thing we need to know about forms in general and form elements in particular is that their dimensions actually depend on the font in use. In other words, to get consistent results across browsers we need to normalize form elements by specifying a font family and size on elements such as input, select and textarea. In this way we get correct dimensions on form elements. Another thing to keep in mind is the default vertical alignment of form elements. These elements are inline-block, except fieldset, label and legend, so we need to use the vertical-align property to normalize their alignment when they appear near inline text.

Said that, let's start with a basic search form:

<form id="search" action="" method="get">
        <input type="text" name="q" id="q" />
        <input type="image" src="path/to/img" alt="Search" id="search-btn" name="search-btn" />

We use an image as the form's submit button. To do so, we also need to specify an alternate text for people who can't see the image. We want the image appear just inside the text field area. Here's the CSS code:

#search {
    width: 23em;
    padding: 0.5em;
    margin: 0;

#search div {
    background: #000;
    color: #fff;
    border: 3px solid silver;
    -moz-border-radius: 6px;
    border-radius: 6px;
    text-align: center;
    padding: 1em;

#search input {
    font: 1em Arial, sans-serif;
    vertical-align: middle;

#search input:focus {
    outline-style: none;

#search #q {
    background: #fff;
    border: none;
    -moz-border-radius: 4px;
    border-radius: 4px;
    width: 15em;
    padding-right: 3em;

#search #search-btn {
    position: relative;
    left: -2em;

The text fields have been normalized using the correct font type and vertical alignment. Then we did prevent a browser from adding an outline to the fields by using the outline-style property when they get focus. Finally, to get the desired effect of the image put inside the field we've used negative relative positioning. To accomplish this task, we've also provided a certain amount of right padding to the text field in order to make it properly host the image.

Just a note about CSS selectors: many readers will probably notice that we could actually use attribute selectors instead of ID selectors to stylize input controls, like so:

input[type="text"] { }
input[type="image"] { }

We didn't do that to get the maximum compatibility from that example. You can see this demo here.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.