1

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?

Matt Coady
  • 3,418
  • 5
  • 38
  • 63

3 Answers3

2

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>    
Niloct
  • 9,491
  • 3
  • 44
  • 57
  • I was hoping to avoid this because I need to fall back to inherited styles (it might not be blue). Also, the 'a' isn't always a direct descendant of that particular attributed div (it could be multiple divs deep). – Matt Coady Jan 10 '19 at 21:15
  • 1
    Tough competition hehe. – Niloct Jan 10 '19 at 21:29
1

Try this:

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

'Greater than' > selects immediate children

luenib
  • 360
  • 3
  • 15
0

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; }
matt lohkamp
  • 2,174
  • 3
  • 28
  • 47