Search code examples
htmlcsscss-selectors

I would like to hide my outer div if inner div is empty


I have two div a child and a parent. the child contains a contact number. If there is no contact number I want the parent div to display none. I am trying to use the :empty CSS statement but I think I am using the wrong logic.

#inter #inter-content:empty {
    display:none;
}
<div id="inter" class="telephone">Intl: <div id="inter-content">{{contact_number_international}}</div></div>

I'm not sure if CSS is the right route either. I have tried using the bottom as well:

#inter + #inter-content:empty {
    display:none;
}

Solution

  • You cant do this in the way you are approaching it due to how CSS works, and that you can only write selectors to isolate child/subsequent DOM nodes. :empty also works on selecting elements with no child nodes (elements or text).

    The :empty pseudo-class represents any element that has no children at all. Only element nodes and text (including whitespace) are considered.

    As such, you cannot select a parent element using CSS- and you cannot determine a node to be empty, if it contains another node (whether that node is empty or not).

    One way to potentially get around this, is to apply the label in your code as a pseudo element, with its content conditionally sourced from a (data) attribute if the element is not empty. This will give the impression of the parent not displaying content if no number is present.

    That said, if you actually dont want to display the parent at all- you will run into trouble using CSS alone. It looks like you are using angular (or similar), in which case you may want to use a logical check to toggle the parent's visibility.

    .inter div:not(:empty):before {
      display: block;
      content: attr(data-label);
    }
    <div class="inter" class="telephone">
      <div data-label="Intl: ">21342213</div>
    </div>
    
    <div class="inter" class="telephone">
      <div data-label="Intl: "></div>
    </div>