Reputation: 183559
The default input type is 'text'. I have 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, I just noticed that my default-type text inputs do not get the styles. Why is this the case? And how can I address this?
input[type='text'] {
background: red;
}
<input name='t1' type='text' /> /* Is Red */
<input name='t1' /> /* Is Not Red */
Upvotes: 76
Views: 265562
Reputation: 46559
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.)
Upvotes: 118
Reputation: 35
To be compliant with all browsers you should always declare the input type.
Some browsers will assume default type as 'text', but this isn't a good practice.
Upvotes: 0
Reputation: 201588
By CSS specifications, browsers may or may not use information about default attributes; mostly the don’t. The relevant clause in the CSS 2.1 spec is 5.8.2 Default attribute values in DTDs. In CSS 3 Selectors, it’s clause 6.3.4, with the same name. It recommends: “Selectors should be designed so that they work whether or not the default values are included in the document tree.”
It is generally best to explicitly specify essential attributes such as type=text
instead of defaulting them. The reason is that there is no simple reliable way to refer to the input
elements with defaulted type
attribute.
Upvotes: 7
Reputation: 78991
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.
Upvotes: 9