Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placeholder text in an input field with CSS only (no JavaScript)

Instead of labeling each field in a form, it is sometimes preferable (from a design standpoint) to have placeholder text in each field. For example, instead of having this:

             ----------------------------------
Full Name:  |                                  |
             ----------------------------------

you have this:

 ----------------------------------
| Full Name                        |
 ----------------------------------

The when you click in the field, the text disappears and you can write whatever you want. If you skip over the field without entering any text, then the placeholder reappears.

I've seen this done many ways, but all methods involve JavaScript. For example, Twitter does a decent job on their signup page but if Javascript is disabled you end up typing your name over the word 'Full name'.

I'm looking for a CSS-only method that would work even with JavaScript disabled. The only potential solution I've come up with is to set the background of the <input> tag to an image of the desired text and then use the input:focus pseudo-class to clear the background image when someone clicks on the text box. This seems to work but it would be nice not to have to use images.

Does anyone know of a good resource on how to do this?

like image 826
David Jones Avatar asked Jul 06 '12 23:07

David Jones


People also ask

Can you set placeholder text in CSS?

CSS ::placeholder SelectorThe ::placeholder selector selects form elements with placeholder text, and let you style the placeholder text. The placeholder text is set with the placeholder attribute, which specifies a hint that describes the expected value of an input field.

Can I use CSS input placeholder?

Only the subset of CSS properties that apply to the ::first-line pseudo-element can be used in a rule using ::placeholder in its selector. Note: In most browsers, the appearance of placeholder text is a translucent or light gray color by default.

How do you insert a placeholder in text field?

If you want to set a hint for text area or input field, then use the HTML placeholder attribute. The hint is the expected value, which gets displayed before the user enters a value, for example, name, details, etc.


1 Answers

This is the preferred method, and works in all current browsers:

<input type="text" name="" placeholder="Full Name"/>

This version works for IE9 and before:

<input type="text" name="" value="Full Name" onfocus="value=''" onblur="value='Full Name'"/>
like image 60
Jay Avatar answered Oct 12 '22 06:10

Jay