1

I'm trying to select all code elements except the one that's a descendant of the pre element using a :not(~) selector. This post has a very similar answer but I'm having a hard time figuring out my problem.

<body>
<div><code>Div Code</code></div> 
<pre><code>Pre Code</code></pre> <!-- Exclude only this -->
<Code>Body Code</Code>
</body>

This selector using :not(~) doesn't seem to work.

code:not(pre code) {
  color:red;
}

The code selector selects all three, and pre code selects only the 2nd one, so shouldn't joining them using :not produce all three except the 2nd one?

What could be wrong here?

I could use a selector other than the :not(~) but it fits the best for my use-case since code element can be nested in other elements and I want to exclude only the descendants of pre.

Thanks in advance.

Harry Cho
  • 2,309
  • 4
  • 20
  • 28
  • Duplicate of https://stackoverflow.com/questions/23853931/how-can-i-style-code-only-if-its-parent-is-not-pre – suprjami Nov 09 '22 at 10:47

2 Answers2

2

If your <code> is always a direct descendant of <pre>, you can use the direct descendant combinator to target it:

:not(pre) > code {
  color:red;
}
<body>
  <div><code>Div Code</code></div> 
  <pre><code>Pre Code</code></pre> <!-- Exclude only this -->
  <Code>Body Code</Code>
</body>

Note: if you removed the >, intuitively, sure, it should work, but since it can target any ancestor, such as <body>, it'll match because body:not(pre) is true.

Elron
  • 1,235
  • 1
  • 13
  • 26
chriskirknielsen
  • 2,839
  • 2
  • 14
  • 24
-1

You can't do that. :not() works only for the tag itself, not parent tags that wrap it.

What you can do, is add a class to <code> like this: <code class="notpre"></code> and add a css rule like this:

code.notpre {
  color:red;
}

You can read more about :not() pseudo-class here.


Edit 1: You can do this that way too, but it's not recommended because it's too "wide" and can affect some unwanted <code> tags. I'd recommend using class names like in the first solution I mentioned.

code {
  color:red;
}
pre code {
  color:initial;
}
<div><code>Div Code</code></div> 
<pre><code>Pre Code</code></pre> <!-- Exclude only this -->
<Code>Body Code</Code>
Elron
  • 1,235
  • 1
  • 13
  • 26