如何在重复模式中选择元素范围 [英] How to select a range of elements in repeated pattern
问题描述
我们假设有4行中有12个项目。
Let's say there are 12 items in 4 rows.
| 1 || 2 || 3 |
| 4 || 5 || 6 |
| 7 || 8 || 9 |
| 10 || 11 || 12 |
我想选择并设置第二行和第四行,我如何做?
I want to select and style 2nd row and 4th row, How do I do that?
请注意,行不在不同的HTML元素中,实际上它们都是ul li元素。
Note that rows are not in different HTML elements, in fact they are all an ul li element.
| 1 || 2 || 3 |
|--4---||--5---||--6---|
| 7 || 8 || 9 |
|--10--||--11--||--12--|
我试过玩过:
li:nth-child(n+4)
选择前三个之后的所有元素。
然后我尝试这个:
It selects all the elements after first three. Then I tried this:
li:nth-child(n+4):nth-child(-n+8)
6但我不能重复这个模式来选择10,11& 12。这在CSS中有什么解决方案吗?
This only selects 4, 5 & 6 but I cant repeat this pattern to select 10, 11 & 12 as well. Is there any solution for this in CSS?
推荐答案
这是一个常见的问题,但我想指出,原因:nth-child(n + 4):nth-child(-n + 6)
只匹配一个特定范围的元素, n + 4)和单个端点(-n + 6)。唯一可以大于或等于4 和小于或等于6的元素是4,5和6,因此使用相同的选择器不可能匹配此范围之外的元素。添加更多:nth-child()
pseudos只会缩小匹配项。
This is a commonly-asked question, but I wanted to point out that the reason :nth-child(n+4):nth-child(-n+6)
only matches one specific range of elements is that it only provides a single start point (n+4) and a single end point (-n+6). The only elements that can be greater than or equal to 4 and less than or equal to 6 are 4, 5 and 6, so it's impossible to match elements outside of this range using the same selector. Adding more :nth-child()
pseudos will only narrow down the matches.
这在列方面,假设每行总是有3列(元素)。您有三列,因此您需要三个分隔 :nth-child()
伪码。第一列中的元素4和10分开6个元素,因此所有:nth-child()
伪元素的参数需要以6n开头。
The solution is to think of this in terms of columns, assuming there will always be exactly 3 columns (elements) per row. You have three columns, so you will need three separate :nth-child()
pseudos. Elements 4 and 10 from the first column are 6 elements apart, so the argument to all of the :nth-child()
pseudos needs to start with 6n.
An + B表达式中的+ b部分可以是+4,+ 5和+6或0,-1和-2 - 它们都将匹配同一组元素:
The +b portion in the An+B expression can either be +4, +5 and +6, or 0, -1 and -2 — they will both match the same set of elements:
-
li:nth-child(6n + 4),li:nth- ),li:nth-child(6n + 6)
-
(6n-1),li:nth-child(6n-2)
li:nth-child(6n+4), li:nth-child(6n+5), li:nth-child(6n+6)
li:nth-child(6n), li:nth-child(6n-1), li:nth-child(6n-2)
与单个:nth-child()
伪类或由:nth-child()
pseudos,因为An + B符号根本不允许这样的表达式被构造为匹配所描述的范围中的元素。
You cannot do this with a single :nth-child()
pseudo-class, or a single compound selector consisting of any combination of :nth-child()
pseudos, because the An+B notation simply doesn't allow such expressions to be constructed that match elements in ranges as described.
这篇关于如何在重复模式中选择元素范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!