Excluding a Parent

programming css selectors

Posted: 2023-02-04

In yesterdays post I used both inline code blocks and larger code blocks to illustrate the advantages of (https://direnv.net)[direnv]. I then noticed that the inline code blocks were not similarly styled as the larger code blocks which are styled according to codehilite.

I naively added my desired styling to all <code> tags but of course this also applied to the large codehilite blocks and added strange behaviour. Looking closer at the html I noticed that codehilite added its styling on a class selector and that all of its <code> tags were the child of a <pre> tag. The question then becomes how do I select all <code> tags which do not have the <pre> tag as a parent.

<code> <-- Select this
    <!-- code here -->
</code>

<pre class="codehilite">
    <code> <-- Do not select this
        <!-- code here -->
    </code>
</pre>

Using the child combinator > and the :not() pseudo class this can be solved. The child combinator allows us to select all <code> tags that have a <pre> parent while the :not() pseudo class flips that selection to instead exclude all <code> tags with a <pre> tag as a parent. The resulting selector end up like below:

:not(pre) > code {
    /* styling */
}

Just a quick little tip today. Hope you find it helpful!

Cheers,
Theo