search

Home  >  Q&A  >  body text

CSS selector (if the element has no specific parent)

If an element doesn't have a certain parent element, I want to change the style of that element without having to overwrite it to its original value.

See https://jsfiddle.net/xqb2z8tc/ The problem with the above code is that due to the heavy use of mixins, it generates a lot of css, so we want to rewrite it. I thought about using the ':has()' selector (browser support is fine for us), but I don't know how.

Similar to the code below, but it should work in all cases, see the jsfiddle above.

.dark-view:not(:has(.obox)) p {
  color: white;
}

P粉092778585P粉092778585316 days ago514

reply all(1)I'll reply

  • P粉949267121

    P粉9492671212024-01-17 10:02:06

    Based on my interpretation of the question, it looks like you want to apply color: #fff to all

    elements in .dark- view is not .obox Descendants of the element. If this is the case, consider using the selector .dark-view p:not(.obox *):

    p {
      color: #111;
    }
    
    .dark-view p:not(.obox *) {
      color: #fff;
    }
    
    /* irrelevant demo stuff */
    .dark-view {
      background: #333;
      padding: 10px;
    }
    
    .obox {
      background: #eee;
      border: 1px solid red;
      padding: 2px;
      margin-bottom: 5px;
    }
    <div class="dark-view">
      
      <div class="obox">
        <p>default</p>
      </div>
      
      <div>
        <div class="obox">
          <p>default</p>
        </div>
      </div>
      
      <div>
        <div>
          <div class="obox">
            <p>default</p>
          </div>
        </div>
      </div>
      
      <p>ondark</p>
      <div>
        <p>ondark</p>
      </div>
    </div>
    
    <p>default</p>
    
    <div class="dark-view">
      <p>ondark</p>
      <div>
        <p>ondark</p>
      </div>
      <div>
        <div>
          <p>ondark</p>
        </div>
      </div>
    </div>

    reply
    0
  • Cancelreply