Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I target text input fields with CSS?

Tags:

html

css

input

Say you have the following HTML:

<input />
<br />
<input type=text />

Of course, in my HTML I'll have other type of input fields as well (checkboxes, etc). Now I want to style the text inputs only.

What I find when searching, is to do the following in CSS:

input[type=text] { background: red; }

For the second input, where the attribute is explicitly present, this works. For the first however, it works in IE8, but not in IE10. Also not in Chrome.

So how can I target all text input fields, and only the text input field, while not having to put type=text everywhere?

You can see this in a jsFiddle. For IE8, check out these instructions on how to get jsFiddle to work, but it looks like this:

enter image description here

like image 399
Peter Avatar asked Jul 17 '13 12:07

Peter


2 Answers

If you want to be able to omit the type="text" and still have the selector match, you will have to use the not psuedoselector available in CSS3:

input[type="text"], input:not([type]) {
    ...
}

http://jsfiddle.net/dByqP/5/

This will not work in lower versions of IE, as CSS3 is not well supported in those browsers.

The best solution would be to go through and add type="text" to your text inputs and just use your original selector.

like image 65
jbabey Avatar answered Oct 28 '22 12:10

jbabey


One painful, but sure way could do is to set the style on simply

input {
    /* ... */
}

Which would target the text input in every browser, then you could do what you were doing, and target every single type of input that is not a text input:

input[type=range] {}
input [type=phone] {}
// etc.

This way, even if the :not operator available in CSS3 is not supported by a browser, you can still get it to work...

like image 25
rodrigo-silveira Avatar answered Oct 28 '22 11:10

rodrigo-silveira