How can I style only if its parent is not <

2020-04-03 12:32发布

I'm integrating wmd-editor like the one used here.

For inline code blocks like this one, the html generated is:

<code>this one</code>

For multiline code like:

var i = 0;
var j = 0;

The html generated is:

<pre>
  <code>var i = 0;</code>
  <code>var j = 0;</code>
<pre>

I've separate css for them: pre{ ... } and code{ ... }

Now, I want <code> style to be applied only if its parent isn't <pre>.

I've tried using code:not(pre code){ ... } but it didn't seem to work.

I can guarantee the HTML structure above.

Can it be solved through css?

Fiddle

2条回答
Ridiculous、
2楼-- · 2020-04-03 12:42

There is no parent selector in CSS. Your only choice is to make style that apply for both for the ones without the <pre> parent, and override those rules with the <pre> selector:

code { color: red; }
pre code { color: blue; } /* More specific, so will override the first! */

Alternative solutions include JavaScript.

查看更多
来,给爷笑一个
3楼-- · 2020-04-03 12:45

:not(pre) > code { … } should do the job, iff the code element is a direct child of the pre element.

查看更多
登录 后发表回答