Home » Html » Does the :not pseudo class increase the specificity of a selector?

Does the :not pseudo class increase the specificity of a selector?

Posted by: admin November 30, 2017 Leave a comment

Questions:

I have read on css tricks that :not should not add additional specificity. But it looks like it does?

https://css-tricks.com/almanac/selectors/n/not/

The specificity of the :not pseudo class is the specificity of its argument. The :not() pseudo class does not add to the selector specificity, unlike other pseudo-classes.

Or am I missing something?

.red:not(.blue) {
  background: blue;
}

.red {
  height: 100px;
  width: 100px;
  background: red;
}
<div class="red">
</div>
Answers:

Yes, it adds the specificity of its argument. Look at the first sentence:

The specificity of the :not pseudo class is the specificity of its argument. The :not() pseudo class does not add to the selector specificity, unlike other pseudo-classes.

So the specificity of .red:not(.blue) is equal to that of .red.blue — 2 class selectors, or (0, 2, 0), making it more specific than .red on its own. What the second sentence means is that the :not() itself does not contribute the additional specificity of a pseudo-class to make it (0, 3, 0), like the :hover in .red.blue:hover does for example.

Questions:
Answers:

The :not selector don’t have it’s own specificity, however the selector inside :not() do have.

From MDN

Selector Types

The following list of selector types is by increasing specificity:

  1. Type selectors (e.g., h1) and pseudo-elements (e.g., :before).
  2. Class selectors (e.g., .example), attributes selectors (e.g., [type="radio"]) and pseudo-classes (e.g., :hover).
  3. ID selectors (e.g., #example).

Universal selector (*), combinators (+, >, ~, ' ') and negation pseudo-class (:not()) have no effect on specificity. (The selectors declared inside :not() do, however.)


As you’re having the rule .red:not(.blue) and the element <div class="red"> don’t have the class blue, the rule is applied.

.red:not(.blue) {
  background: blue;
}

.red {
  height: 100px;
  width: 100px;
  background: red;
}
div {
  background: green;
  width: 50px;
  height: 50px;
  margin: 10px;
}
<div></div>
<div class="red"></div>
<div class="blue"></div>

Leave a Reply

Your email address will not be published. Required fields are marked *