使用CSS,有没有办法选择与某个选择器匹配的元素最近的后代?
<div class="foo"> <!-- if we're inside this -->
<div>
<br />
<div class="bar"> <!-- match this -->
<div class="bar"> <!-- but not this -->
<div class="bar"> <!-- or this -->
</div>
</div>
</div>
<div class="bar"> <!-- I don't really care whether we match this -->
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
也就是说,可以.bar在任何内容中选择第一个.foo(无论中间有多少个子元素或兄弟元素),而不是第二个或第三个元素.bar.
thi*_*dot 14
这是我的解答:http://jsfiddle.net/thirtydot/gqJdP/2/
/*repeat for as many levels as there could be*/
.foo > .bar,
.foo > :not(.bar) > .bar,
.foo > :not(.bar) > :not(.bar) > .bar {
border-color: blue;
}
.bar {
border: 1px solid red;
padding: 10px;
}
Run Code Online (Sandbox Code Playgroud)
引用自己的评论:
我的建议是可行的,虽然令人反感,如果你可以.foo对.bar你想要匹配的父母之间可能的父母数量设置一个上限.即使你不得不重复选择器(让我们说)10次,也不会太糟糕.