The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums CSS Styling li except when a parent div has specific class

  • This topic is empty.
Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
  • #234711

    I’m trying to style li elements, whenever they’re not contained in any div with class=”a”. However, I can’t edit the HTML sourcecode, so I’m looking for a CSS-only solution.

    Best case scenario IMO would be to reference any ‘parent’ path, but that’s not how CSS works. I can’t see a solution, other than specifically styling all occurrences manually (giving me bloated CSS) .

    Please see the fiddle at , any help appreciated!


    I want everything with class=”b” green, except when found in any parent with class=”a”.

    Based on that, you can just target the parent class, no?

    .a .b {
       background-color: transparent;


    Hmmm seems my example was too basic. I was expecting a solution with the :not() selector, as my actual use case is more complex; the div class=”b” represents any li that’s not child of the class=”a” div.

    This li can occur anywhere on the page, within any hierarchical depth as well. It’s never enclosed by specific elements/classes, the only quality is that I want to separate li’s that are either within an a/b class, and the rest.

    I can code several lines to make this working, but IMO something this simple should be containable within a small code footprint, using the :not() selector?



    Yeah, the issue is that you can’t really rely on the :not one, because something like div:not(.a) li would only work if the LI is not within another div.

    I think specificity is the issue here. Let’s say when you have this:

    li {background:red;}
    div:not(.a) li {background:green;}

    Then the LI will still be green if it’s within a nested DIV (with a class that’s not “a”), even when a parent DIV (or grandparent, or….) has class “a”.

    So I guess you’re gonna have to use some JS. Something like this:


    Yeah, I was afraid of that. I thought perhaps using the :not operator could allow for such behavior, but it was a long shot. Thanks! :)

Viewing 6 posts - 1 through 6 (of 6 total)
  • The forum ‘CSS’ is closed to new topics and replies.