Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

css - Excluding an element from nth-child pattern

Let's say I have these elements:

<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>

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.

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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;
}

and so on (see updated fiddle).

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...