仅使用 css,将 css 样式添加到 .apply-style-here 的父级(不带 .second-stage 类)
P粉798010441
P粉798010441 2023-09-11 14:23:08
0
1
579

如何通过仅满足此条件将样式应用于 .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>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板