I learned about selector precedence from this tutorial. I have trouble understanding the behavior of this in one case. I have an element in HTML:
<input class="top_bar_login_form_input" type="text" name="email" placeholder="Prijavno ime">
The problem is that properties from another selector override the properties from the class.
As shown in the picture above the class gets overridden by a less specific selector. The element gets selected by input[type="text"]
, which is less specific than a class. The only reasoning behind these behavior that I see is that the .inputbox
class is also calculated in determining the precedence, even though it doesn't match the element.
Why does the type selector override the class selector?
TL;DR Answer
The first rule is more specific than the second one because it has both a type and attribute part for the selector, and thus has precedence:
input[type="text"] { } /* type + attribute for specificity */
.top_bar_login_form_input { } /* only class for specificity, so *less* specificity */
Longer answer
You'd think that the type="text"
bit, which is an attribute selector, is more specific than a class selector, in accordance with the MDN page on specificity:
The following list of selectors is by increasing specificity:
- Universal selectors
- Type selectors
- Class selectors
- Attributes selectors
- Pseudo-classes
- ID selectors
- Inline style
The above quote was in the MDN article at the time this answer was written.
Why that is misleading:
(Tanks to @BoltClock's insights.)
The above only seems correct, but that's because you typically include the element in the selector (e.g. input[type="text"]
) when doing an attribute selector. However, what's sneaky: the input
bit matters.
Suppose we have the following markup:
<input class="my-class" type="text" value="some value" />
In the following scenario the input renders red:
[type="text"] { color: green; }
.my-class { color: red; } /* last rule matched */
If we reverse the rules in a scenario, the input will render green:
.my-class { color: red; }
[type="text"] { color: green; } /* last rule matched */
This is because both selectors have equal specificity. Now introducing the input
selector to the attribute rule will make one of them more specific, which can be seen in this scenario:
input[type="text"] { color: green; } /* most _specific_ rule matched */
.my-class { color: red; }
The W3 spec makes my head hurt, but it does have the details on why the above works. See also the answer by @BoltClock and comments in those code examples for info on how the specificity is calculated.