csscss-selectors

Hide an element if the next one is empty


I have the following code :

<h3 class="hideIfDivEmpty">title</h3>
<div id="divId"></div>

I would like to hide the h3 element when the div is empty. I'm willing to change the html structure but the h3 has to be outside of the div because its content is dynamically changed.

Is there a way to do that in CSS ?


Solution

  • There is no syntax to select a parent element or any other non-child element from #divid. You can select #divid if it's empty, by #divid:empty, but there is no way you can select .hideIfDivIsEmpty in any browser by selecting that. According to this question there is such a thing in CSS4 (specs), but it is not supported in any browser as of now and according to the same specs, the selector is too slow to be implemented in browsers.

    See the other answers for the javascript solution to this problem.