我可以使用纯 CSS 根据元素的祖先位置属性设置元素的样式吗?



是否可以根据元素祖先的CSS属性值选择元素?假设我有以下 HTML 文本:

<div><!-- ancestor -->
<!-- I may have N level descendants which are as well ancestors for the upcoming div -->
<div class="myTarget">
The div I want to target
</div>
</div>

我对祖先一无所知,除了如果其中一个具有CSS属性display: table-cell那么我希望myTarget拥有position: absolute,否则应该position: relative

.myTarget {
position: relative;
}
/*************************************************************************************************
* This is actually the question, how to target .myTarget when some ancestor div contains a given
* cssProperty. Code below is just pseudo-code not actual CSS.
*************************************************************************************************/
div[cssProperty=desiredValue] .myTarget {
position: absolute;
}

我的猜测是我不能,但由于可以根据元素的属性选择元素,我认为也许它也应该是一种基于其 CSS 属性进行选择的方法。

我的解决方案是一个类:

<div class="ancestor"> <!-- ancestor -->
<div class="myTarget">
The div I want to target
</div>
</div>

和 css:

.myTarget {
position: relative;
}
div.ancestor > .myTarget {
position: absolute!important;
}

最新更新