无子但非空的 CSS 选择器

2022-01-10 00:00:00 css-selectors html css

我想在下面的 HTML 片段中选择 BONKERS.它的区别在于它在 <code> 块中是单独的,而它的所有兄弟都包含 <a> 的.:empty 是显而易见的选择,但由于文本节点而无法使用.我以为我知道这些东西,但这让我发疯了.

I want to select BONKERS in the HTML fragment below. Its distinction is that it's alone in a <code> block whereas all its siblings contain <a>'s. :empty is the obvious choice, but won't work due to the text node. I thought I knew this stuff but this is driving me, well, bonkers.

 <ul class="Reference">
    <li class="level4">
        <code class="active-voice">
            <a href="some/url/x" version="2">
                mauve 
            </a>
    </code>
    <li class="level8">
        <code class="active-voice">
            BONKERS 
        </code>
    </li>
    <li class="level9 subclass">
        <code class="active-voice">
            <a href="some/url/c" version="2">
                cerise 
            </a>
    </code>
    </li>
</ul>

我需要一个纯 CSS 解决方案(JS 不是一个选项),并且无法控制源 HTML.

I need a pure CSS solution (JS isn't an option), and have no control over the source HTML.

呸!

推荐答案

你可以按照这个方法.通过您想要的任何 CSS 设置 code 元素的样式,然后重置那些在 anchor 的样式中可继承的 CSS 样式,即:

You can follow this approach. Style the code elements by whatever CSS you want and then reset those CSS styles which are inheritable in anchor's styles i.e.:

演示:http://jsfiddle.net/GCu2D/1062/

CSS:

code {
    color: green;
    font-weight: bold;
}
code a{
    color: red;/*Reset any inheritable css*/
    font-weight: normal; /*Reset any inheritable css*/
}

您可能不需要重置所有样式,因为并非所有样式都由 anchorcode 元素继承

You might not need to reset all styles because not all styles are inherited by anchor from the code element

这是您真正可以考虑的一种解决方案.

This is one solution which you can really consider.

相关文章