3

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.

Don P
  • 49,839
  • 95
  • 259
  • 394

2 Answers2

4

No, it is impossible to address parent from children with CSS. You should use JavaScript to do so, for example with jQuery .parent() method.

Michał Perłakowski
  • 70,955
  • 24
  • 137
  • 155
IdeaMan
  • 669
  • 4
  • 13
2

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();
});
Gaurav Aggarwal
  • 8,921
  • 5
  • 27
  • 65
  • 1
    Suggesting something as large as jQuery for the equivalent elem.parentNode in vanilla JS is bad practice. – Zach Saucier Apr 06 '16 at 13:18
  • @ZachSaucier I agree with the sentiment but when 79% of websites run jQuery and there's no widely available CSS solution, it provides the simplest to implement solution for the majority of SO's copy/paste web devs. Any user capable of implementing a vanilla JS solution would also know this. Perhaps a vanilla JS implementation would be preferable to criticism of an ultimately accepted answer. – Andy Gee Sep 14 '20 at 03:38