March 7, 2012

input[type='text'] CSS selector does not apply to default-type text inputs?

Question by Yarin

The default input type is ‘text’. I’ve always assumed then that css declarations targeting input[type='text'] would affect those inputs even if the type was not explicitly declared on the control. However, just noticed that my default-type text inputs don’t get the styles. Why is this the case?

CSS:

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

HTML:

<input name='t1' type='text'/> /* Is Red */
<input name='t1'/> /* Is Not Red */

http://jsfiddle.net/LhnNM/

Answer by Mr Lister

The CSS uses only the data in the DOM tree, which has little to do with how the renderer decides what to do with elements with missing attributes.

So either let the CSS reflect the HTML

input:not([type]), input[type="text"]
{
background:red;
}

or make the HTML explicit.

<input name='t1' type='text'/> /* Is Not Red */

If it didn’t do that, you’d never be able to distinguish between

element { ...properties... }

and

element[attr] { ...properties... }

because all attributes would always be defined on all elements. (For example, table always has a border attribute, with 0 for a default.)

Answer by Starx

Because, it is not supposed to do that.

input[type=text] { } is an attribute selector, and will only select those element, with the matching attribute.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!