Sometimes stylizing a form input field is something that we have to learn by experience. As always, a trial-and-error approach is the best way to acquire a firm knowledge of a technique. Suppose that you have a text field like this:
<input type="text" name="query" id="query" />
Now imagine that you want to use a background image on this field, something like a 200 x 20 GIF image with rounded corners and a surrounding shadow. An innocent coder would be tempted to write something like this:
input#query { border: none; width: 200px; height: 20px; background: url("text-field.gif") no-repeat; }
It does work, but there's a major drawback with this approach: the text cursor appears on the very left edge on the field and not where it was supposed to appear. So you have a cursor that blinks almost outside the field and this is not the effect you want to achieve. Why this? Two considerations:
- the dimensions of this kind of form elements are not simply given by a width or height declaration, but also (and mostly) by the font size and family used on them; so if you want to get consistent results across browsers, you have to specify a font family and size that equals that used on the page (or at least on the direct ancestor of the element), because browsers assign by default a proprietary font family and size to this kind of elements
- input fields are not block-level elements, but inline-block elements, so you have to consider the fact that their rendering is treated differently.
A good solution to this problems is as follows:
input#query { border: none; width: 200px; padding: 5px; background: url("text-field.gif") no-repeat; }
Instead of declaring height: value
on the element, we use padding to make sure that the text cursor will be placed exactly where we want (obviously we have to adjust the amount of padding required to show the background image entirely). This is a cross-browser approach with no drawbacks.