Matt Coady
Matt Coady

Reputation: 3856

Select elements which are not a child of something with a particular attribute property

Essentially I want all "a" elements to be red, except in situation where they are a descendant child of an element with an attribute property of "data-foo".

This html:

<div data-foo="whatever">
  <div>
    ... more descendants 
       <a href="#">I should be default color</a>
  </div>
</div>

<a href="#">I should be red</a>

With this CSS:

:not([data-foo]) a {
  color: red;
}

In this example still selects both "a" elements. I also tried the following:

div:not([data-foo]) a
*:not([data-foo]) a
div:not([data-foo]) a
*:not(div[data-foo]) a

But I'm either getting nothing selected or all selected. Is this a possible selection to make?

Upvotes: 1

Views: 52

Answers (3)

Niloct
Niloct

Reputation: 9995

You could add two rules, one for all A and the other for [data-foo] > a with color: unset; (or the specific color you want):

A {
    color: red;
}

[data-foo]  A {
    color: inherited; 
}
<div data-foo="whatever">
  <a href="#">I should be default color</a>
</div>

<a href="#">I should be red</a>    

Upvotes: 2

Matt Lohkamp
Matt Lohkamp

Reputation: 2191

easy - first set the more general rule (all anchors are red), and then make a specific exception (except for the ones that have an ancestor with the 'data-foo' attribute):

a { color:red; }
[data-foo] a { color:inherit; }

Upvotes: 0

luenib
luenib

Reputation: 370

Try this:

:not([data-foo]) > a {
  color: red;
}

'Greater than' > selects immediate children

Upvotes: 1

Related Questions