2

I want to select all <img> elements that are inside an <article> and not inside a <figure>

Following these 2: How to create a css rule for all elements except one class?

https://www.w3.org/TR/css3-selectors/#negation

All <img> are wrapped in <a> or <p>. It seems it could be done with negation. My rule right now looks like this:

article *:not(figure) img { border: 2px solid red; }

Any tips tricks on why this is not working?

Community
  • 1
  • 1
Vaino
  • 33
  • 1
  • 7

1 Answers1

3

It's working, but you're telling the browser that img elements do have to be wrapped in something. So img tags directly inside the article tag will not work, but anything nested e.g. in a div will:

article *:not(figure) img { 
  border: 2px solid red; 
}
<article>
  <img src="//placehold.it/50">
  <figure class="x">
    <img src="//placehold.it/50">
  </figure>
  <div>
    <img src="//placehold.it/50">
  </div>
</article>

What you probably need:

article *:not(figure) img,
article > img{ 
  border: 2px solid red; 
}
<article>
  <img src="//placehold.it/50">
  <figure class="x">
    <img src="//placehold.it/50">
  </figure>
  <div>
    <img src="//placehold.it/50">
  </div>
</article>

Please, do consider the advice from the comments, and see if your situation doesn't allow for an alternative solution that does not use the * universal and :not selector. E.g. this may be a lot simpler:

article img {
  border: 2px solid red; 
}

article figure img { 
  border: none; 
}
<article>
  <img src="//placehold.it/50">
  <figure class="x">
    <img src="//placehold.it/50">
  </figure>
  <div>
    <img src="//placehold.it/50">
  </div>
</article>

But whether that's usable for you depends on the entire context.

Jeroen
  • 60,696
  • 40
  • 206
  • 339
  • The universal selector is stupidly fast - it's a guaranteed match, and probably ignored by the browser in this context anyway. It's the :not() that's "slow" because it's one additional instruction to the browser, and it's only "slow" in that it's not optimized for a critical path unlike tagnames, ids and classes. Utilizing the cascade here is simply a no-brainer - you don't really need to come up with a reason for it. – BoltClock May 23 '16 at 13:04
  • @BoltClock Thanks for your feedback. It makes intuitive sense + I'll take your word for it. At any rate, I don't presume to know much about relative performance of selectors anyways. I've rewritten my answer slightly, weakened/removed claims about speed of selectors. As far as I can tell, even without details on perf, the post should be able to help OP. – Jeroen May 23 '16 at 13:15