从第n个子模式中排除元素 [英] Excluding an element from nth-child pattern

查看:102
本文介绍了从第n个子模式中排除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这些元素:

<li class="class1">content</li>
<li class="class1">content</li>
<li class="class1 class2">content</li>
<li class="class1">content</li>
<li class="class1">content</li> <!-- I want nth-child(4n) to select this-->
<li class="class1">content</li>
<li class="class1">content</li>
<li class="class1">content</li>

我想使用 .class1:nth-​​child(4n)选择每4个元素,但如果一个元素有BOTH class1 class2

I want to use a .class1:nth-child(4n) to select every 4th element, but if an element has BOTH class1 and class2 I don't want it to be included in the "every 4th" counting--I just want it to be ignored.

我尝试过 .class1 :not(.class2):nth-​​child(4n),但它似乎不工作。任何想法?

I've tried .class1:not(.class2):nth-child(4n), but it doesn't seem to work. Any ideas?

这是一个JSFiddle实验: http: //jsfiddle.net/jWxb6/2/

Here's a JSFiddle for experimentation: http://jsfiddle.net/jWxb6/2/

推荐答案

nth-child selector只计算任何子节点,因此 .class1:nth-​​child(4)表示容器的第四个子元素 class1 class',而不是'容器中该类的第4个元素'。 nth-of-type 选择器只能选择特定类型(标签名称)的元素,因此您可以,例如count dt dl 列表中的 dd 元素分开。在 nth-child(.class1的4) pseudorel =nofollow> CSS选择器4 草稿,但目前支持只有在最新版本的Safari中。

nth-child selector just counts any child nodes, so .class1:nth-child(4) means 'element that is the 4th child of the container and has class1 class', not 'the 4th element with that class in the container'. The nth-of-type selector can select only elements of the specific type (tag name), so you can, e.g., count dt elements separately from dd elements in a dl list. There is nth-child(4 of .class1) syntax in CSS Selectors 4 draft, but it's currently supported only in the latest versions of Safari.

使用大多数浏览器支持的CSS,您可以在要排除的元素之后重置计数器从列表的剩余部分计数和启动新计数器:

With the CSS supported by most browsers, you can 'reset the counter' after the element you want to exclude from counting and 'start the new counter' for the remaining part of the list:

.class1:nth-child(4n) {
    list-style-type: circle;
}

.class1.class2, .class2 ~ .class1:nth-child(4n) {
    list-style-type: disc;
}
.class2 ~ .class1:nth-child(4n + 1) {
    list-style-type: circle;
}

等等(见 updated fiddle )。

and so on (see updated fiddle).

并使用不同的标签,而不是类和 nth-of-type

Alternatively, you can change the markup and use different tags instead of classes and nth-of-type.

这篇关于从第n个子模式中排除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆