简体   繁体   中英

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:

<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:

.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. I want an .item-part to be outlined only if its closest .item is .is-active .

I'd rather not use JS for this nor a direct-sibling selector since the html may differ. 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):

.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); this is the only solution I can think of...

Just override the style for when your element doesn't have an is-active class:

.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.

JSFiddle demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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