只使用 css,將 css 樣式新增至 .apply-style-here 的父級(不含 .second-stage 類別)
P粉798010441
P粉798010441 2023-09-11 14:23:08
0
1
606

如何透過僅滿足此條件將樣式套用至 .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粉798010441
P粉798010441

全部回覆(1)
P粉814160988

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

: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>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板