搜尋

首頁  >  問答  >  主體

只使用 css,將 css 樣式新增至 .apply-style-here 的父級(不含 .second-stage 類別)

如何透過僅滿足此條件將樣式套用至 .apply-style-here 的父 div

  1. .apply-style-here 的父級應該是普通 div 或沒有 .second-stage 類別
  2. .apply-style-here 父級的父級不應該有 .second-stage 謝謝
<div class="first-stage">
    <div>
        <div class="apply-style-here">Content</div>
    </div>
</div>

<div class="first-stage">
    <div class="second-stage">
        <div>
            <div class="apply-style-here">Content</div>
        </div>
    </div>
    <div>
        <div class="apply-style-here">Content</div>
    </div>
</div>

嘗試解決辦法

/* Result: Put border to all parent of apply-style-here class */
.first-stage:has(div > .apply-style-here) > div {
/*  margin-top: 20px; */
  border: 1px solid red;
}

/* Result: No styles applied at all */
.first-stage:not('div > .second-stage') > div {
  border: 1px solid blue;
}

/* Result: No styles applied at all */
.first-stage:has(div:not('.second-stage') > .apply-style-here) > div {
    border: 1px solid blue;
}

/* Result: Applied to all .apply-style-here even second .second-stage is present */
.first-stage:has(div:not(.second-stage) > .apply-style-here) > div {
    border: 1px solid blue;
}
/* Result: Applied to all .apply-style-here even second .second-stage is present */

.first-stage:has(div:not(.second-stage > .apply-style-here)) > div {
    border: 1px solid blue;
}

P粉798010441P粉798010441502 天前609

全部回覆(1)我來回復

  • P粉814160988

    P粉8141609882023-09-12 00:17:50

    根據您的描述,以下選擇器可以工作:

    :not(.second-stage) > :not(.second-stage) > .apply-style-here

    :not(.second-stage) > :not(.second-stage) > .apply-style-here {
      border: solid 1px blue;
    }
    <div class="first-stage">
        <div>
            <div class="apply-style-here">Content</div>
        </div>
    </div>
    
    <div class="first-stage">
        <div class="second-stage">
            <div>
                <div class="apply-style-here">Content</div>
            </div>
        </div>
        <div>
            <div class="apply-style-here">Content</div>
        </div>
    </div>

    回覆
    0
  • 取消回覆