CSS Inheritance : Override an ID parent selector with a CLASS child

2k views Asked by At

I have browsed several topics about the CSS inheritance but no one gave me an answer to a specific use case which is producing an unwanted behavior.

Reproduction of the problem with a simple example

<html>
    <head>
        <style>
        #content a { color:red; }   /* Theme selector (unmodifiable) */
        a.child { color:blue; }     /* Plugin selector */
        </style>
    </head>
    <body>
        <div id="content">
            <a class="child" href="http://www.stackoverflow.com">
            stackoverflow
            </a>
            <a class="child" href="http://www.stackoverflow.com">
            stackoverflow
            </a>
        </div>
    </body>
</html>

As you know, the ID is more prior than the CLASS, so the second rule is ignored.


Description of the real use case issue

Unfortunately, I have encountered this inheritance problem in a more complex use case, which includes WordPress CMS.

Indeed, WordPress contains a functionality called a theme. A theme is a kind of package which the developer is not very likely to modify. Besides, WordPress CMS contains plugins that are pluggable on the theme.

Let's imagine the CSS rules #content a is defined in the theme StyleSheet and cannot be modified (I don't want to change the style of the theme and change #content for .content for example...). Then, the second rule a.child is defined on my plug-in, which is, in contrary to the previous rule, modifiable.

In other words, the problem is the following:

  • I want to override the first rule #content a by applying a style to the <a class="child"> element with a clever selector. The real question is whether we will manage to find, together, a workaround to break the ID priority.

I definitely do not want to use :

  • Hacky solutions (like !important)
  • #content selector on the overriding child selector, which will totally break the modularity of my plugin. Indeed, the following selector works but its usage is totally unthinkable in my code : #content a.child { color:blue; }

I'm sorry for the complexity of my use case, but please, help to find a solution

1

There are 1 answers

0
Jacob On

I know you said no !important, but the below code would limit its use to if the parent container has an id. I too have experienced this problem when styling CMS themed sites.

#content a { color:red; }   /* Theme selector (unmodifiable) */
a.child { color:blue; }     /* Plugin selector */

[id] > a.child { color: blue !important; }
<div id="content">
    <a class="child" href="http://www.stackoverflow.com">
        stackoverflow
    </a>
    <a class="child" href="http://www.stackoverflow.com">
        stackoverflow
    </a>
</div>