简体   繁体   English

限制CSS选择器范围

[英]Limit CSS selector scope

This is a bit weird and maybe is wrong but that's what I want to do... 这有点奇怪,也许是错误的,但这就是我想要做的...

My HTML looks like this: 我的HTML看起来像这样:

<div class="item is-active">
    <div class="item-part"></div>

    <div class="item small">
        <div class="item-part">

        </div>
    </div>
</div>

And with CSS I want to do this: 并使用CSS,我想这样做:

.item.is-active  .item-part {
    outline:1px solid red;
}

The problem is that the inner .item-part will also be outlined which is not desirable. 问题在于内部的.item-part也将被概述,这是不希望的。 I want an .item-part to be outlined only if its closest .item is .is-active . 我希望仅当最接近的.item.item .is-active时才概述.item-part

I'd rather not use JS for this nor a direct-sibling selector since the html may differ. 我宁愿不使用JS也不使用direct-sibling选择器,因为html可能有所不同。 I also don't want to override the rule like this: 我也不想覆盖这样的规则:

.item:not(.is-active) .item-part {
        outline:none;
}

Here is a fiddle with a live example 这是一个生动的例子

Thank you. 谢谢。

How about (Assuming only one element has the is-active class): 怎么样(假设只有一个元素具有is-active类):

.item.is-active .item-part {
    outline:1px solid red; /* active item part style */
}
.item.is-active .item .item-part {/* e.g. child of iten that is not active*/
    outline: none; /* disable active item part style */
}

If you can't modify the class names, won't use javascript, and the direct descendant solution doesn't work (eg because there may be wrapper-div's sometimes); 如果您不能修改类名,请不要使用javascript,并且直接后代解决方案将不起作用(例如,由于有时可能有wrapper-div的原因); this is the only solution I can think of... 这是我能想到的唯一解决方案...

Just override the style for when your element doesn't have an is-active class: 当您的元素没有is-active类时,只需重写样式即可:

.item.is-active  .item-part {
    outline:1px solid red;
}

.item.is-active .item .item-part,
.item .item-part {
    outline:none;
}

The .item.is-active .item-part has higher specificty than the .item .item-part selector, so this will always be applied to the .item-part descendants. .item.is-active .item-part具有比.item .item-part选择器更高的特异性,因此它将始终应用于.item-part后代。

JSFiddle demo . JSFiddle演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM