css

Use CSS to hide the parent of a selected element


Using only CSS, is it possible to hide a parent element if a child element does not have a class?

<!-- hide this -->
<div class="parent">
  <p class="badChild" />
</div>

<!-- do not hide this -->
<div class="parent">
  <p class="goodChild" />
</div>

Unfortunately, I cannot change the markup of the page. I can only add CSS rules.


Solution

  • Well you code was wrong <p class="badChild"/> is wrong because <p> is a block element and ends like this <p class="badChild"></p> i have updated the question and coming to your problem there is no method to do this with css only because css allows you to select child, first child, sibling but not the parent element so javascript or jquery is the only option.

    If there was a way to do it, it would be in either of the current CSS selectors specs:


    The Selectors Level 4 Working Draft includes a :has() pseudo-class that works the same as the jQuery implementation. As of 2015, this is not available in any browser.

    Using :has() the original question could be solved with this:

    li:has(> a.active) { /* styles to apply to the li tag */ }
    

    In the meantime, you'll have to resort to JavaScript if you need to select a parent element.

    $(document).ready(function(){
        $('.badChild').parent('.parent').hide();
    });