> Combining :nth-of-type() and :not3
如何在一组元素中对每个(为了参数的缘故)奇数元素应用特定的css样式,同时考虑一组排除元素?
这个问题在这里被复制(显示在代号中):
http://codepen.io/houdmont/pen/VLOBBG
应用了.foo类的一系列元素:
<a href="#" class="foo">1. Blue</a> <a href="#" class="foo">2. Green</a> <a href="#" class="foo">3. Blue</a> <a href="#" class="foo bar">4. Hidden (blue)</a> <a href="#" class="foo bar">5. Hidden (blue)</a> <a href="#" class="foo bar">6. Hidden (blue)</a> <a href="#" class="foo">7. Green</a>
当应用了.bar类时,元素被隐藏.
我想使用.foo应用的剩余元素被称为奇/偶.
尝试如下:
.bar { display: none; } /** * This clearly doesn't work as I'd hoped it would. */ .foo:not(.bar):nth-of-type(even) { color: green; }
理想情况下,我希望第七个元素是绿色的,即使它是一个“奇怪”的元素,如果我能够排除元素与类.bar然后它将是第四个元素,因此被认为是“偶”,设置颜色到绿色.
这可能是CSS吗?
解决方法
CSS is fully declarative; every selector is a simple condition that is true or false independently of any selector part. It’s not a procedural language where you take a set and process it,narrowing it down with each step. A selector language with procedural rules would be immune to many kinds of optimisation and would be slower.
So nth-of-type is only about position within an element’s parent,and not position in a ‘results list so far’ because CSS selectors have no such concept. A selector engine could look up the test for nth-of-type before narrowing it with not,as the rules do not interfere with each other.