简体   繁体   中英

Using CSS :not selector in LESS nested rules

.outerclass {
    h3 {
        color: blue;
    }
    p:not(.nested) {
        color: green;
    }
}

In the LESS example above I wish to target all "p" elements within a div class "outerclass" but NOT the p elements within the further nested div called ".nested" - it does not work but instead makes all p elements green. I have tried...

p:not(.nested p) // excludes all p elements 

and also...

p:not(.nested > p) // excludes all p elements 

...to no avail. Is this possible or what am I missing? I am brand new to LESS

It is not a LESS issue as much as your css selector syntax. The p:not(.nested) is saying all p elements without the .nested class themselves , what you state is that the .nested class is on a div in which the p resides, so you need this:

.outerclass {
    h3 {
        color: blue;
    }
    :not(.nested) p,
    > p {
        color: green;
    }
}

UPDATE: I removed the div and added the direct child p instance, so that the CSS output would properly target all p in .outerclass except for the exception.

CSS Output for p elements would be

.outerclass :not(.nested) p,
.outerclass > p {
  color: green;
}

The above will target any direct child p elements and any nested p elements in .outerclass except those that are children of your .nested element.

An issue

The issue BoltClock is noting is if the p is nested deeper than being the immediate child of the .nested element. See this fiddle where the last p element is still targeted even though it is within a .nested class .

If the p element will always be the direct child of .nested there is no issue. Or if the .nested is always the direct child of .outerclass but the p maybe nested deeper, then the above selector can be changed to > :not(.nested) p to produce CSS of .outerclass > :not(.nested) p which will then work for all p under .nested .

The problem will be if the .nested in relation to .outerclass and the p within .nested are both at some arbitrary depth to those parents . No css selector could handle that adequately.

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