skip to Main Content

I have the following element structure:

<div class="general">

    <div class="general-container">

        <div class="general-grid">

            <div class="general-wrapper"></div>

        </div>

    </div>

</div>

I’m trying to not display the general div when the general-wrapper is not having any child elements.

So first tried this:

.general-wrapper:not(:has(*)) {
background-color:red;
}

Which works.

Then this:

.general-container:has( .general-wrapper ) {
background-color:green;
}

Which also works.

But when I combine them it doesn’t.

.general-container:has( .general-wrapper:not(:has(*) ) ) {
display:none; // it does display, while it should not :(
}

codepen link:
https://codepen.io/Redox-FGL/pen/LYKgZzq

What I’m doing wrong or not getting?

Note: not looking for a solution with empty, there are more variables here and empty is not working. Need to check on child elements.

2

Answers


  1. Do this instead:

    .general-container:not(:has(.general-wrapper > *)) {
      border: 2px solid red;
      height: 100px;
    }
    <div class="general">
    
      <div class="general-container">
    
        <div class="general-grid">
    
          <div class="general-wrapper">
          </div>
    
        </div>
    
      </div>
    
    </div>
    Login or Signup to reply.
  2. You can set general-container to display none and then set it to display block, for example, if the wrapper has content.

    /* don't display general when general-wrapper has no children */
    
    
    /* so display general when it does have children,otherwise display: none */
    
    .general {
      display: none;
      width: 200px;
      height: 200px;
      background: pink;
    }
    
    .general:has(.general-wrapper > *) {
      display: block;
    }
    <h2>WITHOUT CONTENT</h2>
    <div class="general">
    
      <div class="general-container">
    
        <div class="general-grid">
    
          <div class="general-wrapper">
          </div>
    
        </div>
    
      </div>
    
    </div>
    <h2>WITH CONTENT</h2>
    <div class="general">
    
      <div class="general-container">
    
        <div class="general-grid">
    
          <div class="general-wrapper">
            <div></div>
          </div>
    
        </div>
    
      </div>
    
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search