Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply different styles to input text field when empty (using CSS)?

Tags:

css

For instance, a freshly loaded form contains an <input type="text"> which has a green background colour. Once the user enters a value into the field, I would like it to be coloured blue instead.

Is it possible to accomplish this purely using CSS? I understand there is the input[type='text'][value] selector. However, this does not reflect any changes to the form made by the user after it has finished loading, so if the form loaded with no value, it would remain unchanged regardless of what the user does.

like image 464
Alkenrinnstet Avatar asked Dec 29 '11 15:12

Alkenrinnstet


2 Answers

You could give the textfield the required attribute:

<input type="text" required />

and then check for validity with CSS:

input:invalid { background: green; }

or the opposite (only different for old browsers):

input:valid { background: blue; }
like image 188
Rudie Avatar answered Sep 20 '22 23:09

Rudie


You can only do this using JavaScript. Here's an example that uses jQuery.

If you want to change the background-color on focus only, you can use the aptly named :focus pseudo-selector. Here's an example of this.

like image 31
Josh Smith Avatar answered Sep 23 '22 23:09

Josh Smith