简体   繁体   English

将CSS选择器限制为最近的父选择器

[英]Limit a CSS selector to the nearest parent

If I have this DOM structure 如果我有这个DOM结构

<div class="a b">
  <div class="c" id="c1">
    <div class="a">
      <div class="c" id="c2">
      </div>
    </div>
  </div>
</div>

I would like to create a selector like 我想创建一个类似的选择器

.ab .c { ...} .ab .c {...}

And have it only apply to id=c1 and not id=c2 because the "a" element c2 is inside of doesn't have "b" too. 并且它只适用于id = c1而不是id = c2,因为“a”元素c2在其中也没有“b”。

But currently c2 is also inside a much higher parent that has "a" and "b" so the selector applies. 但是目前c2也位于一个更高的父级中,它具有“a”和“b”,因此选择器适用。

Note that there could be more parents in the chain between "a" and "c". 请注意,“a”和“c”之间的链中可能有更多父母。 I could do this in Javascript/jquery but I'd like a pure CSS solution. 我可以在Javascript / jquery中做到这一点,但我想要一个纯CSS解决方案。

You can use child combinator selector > to target the child elements with a specific parent element - see a demo below where the #c1 is targeted with a red color & a pseudo element. 您可以使用子组合子选择器>使用特定的父元素来定位子元素 - 请参阅下面的演示,其中#c1以红色和伪元素为目标。

Now you can have the selector (see how a pseudo applies only to #c1 ), but the parent styles will be inherited. 现在您可以拥有选择器 (请参阅伪如何仅适用于#c1 ),但父样式将被继承。 So you would have to reset the styles. 所以你必须重置样式。 ( color: initial in the demo below) color: initial下面的演示中的color: initial

 .ab .c { color: initial; } .ab > .c { color: red; } .ab > .c:before { content: '1. '; } 
 <div class="ab"> <div class="c" id="c1">one <div class="a"> <div class="c" id="c2">two </div> </div> </div> </div> 

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

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