NoBugs
NoBugs

Reputation: 9492

Why doesn't css :not work in some cases?

Why does the :not selector not work at all in this case:

a {
  color:red;
}

div a:not(.special a) {
  color: green;
}

In, for example:

<div>
  <span>hello<a href="#">link</a></span>
</div>
<div class="special">
  <span>hello<a href="#">link</a></span>
</div>
<p>
  <a href="#"> something else</a>
</p>

Demo: https://jsfiddle.net/eguecrvz/

Upvotes: 1

Views: 58

Answers (3)

Michael Benjamin
Michael Benjamin

Reputation: 371889

Why doesn't css :not work in some cases?

div a:not(.special a) {
   color: green
}

Because the negation pseudo-class (:not) only takes a simple selector as an argument.

Your argument (.special a) represents a descendant selector which does not qualify.

6.6.7. The negation pseudo-class

The negation pseudo-class, :not(X), is a functional notation taking a simple selector (excluding the negation pseudo-class itself) as an argument. It represents an element that is not represented by its argument.

What is a simple selector?

4. Selector syntax

A simple selector is either a type selector, universal selector, attribute selector, class selector, ID selector, or pseudo-class.

Upvotes: 1

ketan
ketan

Reputation: 19341

special is class of div not anchor.

Change css like:

div:not(.special) a{
  color: green;
}

Fiddle

Edit:

If you want all link green except .special the do like:

a {
  color:green;
}

.special a{
   color: red;
}

Updated Fiddle

Upvotes: 1

BoltClock
BoltClock

Reputation: 724342

:not() currently doesn't allow combinators or any more than one simple selector (such as .special or a) as an argument. A future specification will expand :not() to accept any number of complex selectors, and once browsers support it your selector div a:not(.special a) will work exactly as intended.

In the meantime, it is not possible to write a selector for "an a element that does not have a .special ancestor element." You will need to override with an additional .special a selector in your rule that applies to a elements in general:

a, .special a {
  color:red;
}

div a {
  color: green;
}

The additional specificity of .special a will ensure that it overrides div a, but if specificity is a problem you will need to rearrange your rulesets.

Upvotes: 1

Related Questions