css - 多个第 n 个子语句

标签 css css-selectors

我正在尝试拥有一组特定的第 n 个子序列。

我想为前 10 个事件应用某种样式,但在前 10 个事件之后,我想为每 15 个事件应用另一种样式。

我尝试了 2 个 nth-child 语句,但我还没有弄明白

&:nth-child(10n) {color:red;page-break-after:always;}
&:nth-child(10n+15) {color:blue;page-break-after:always;}

enter image description here

我稍微更新了代码以使其更清晰,并添加了一张图片。

最佳答案

如果我没理解错的话,您希望第 10 个元素之后的每个第 15 个元素都是蓝色的?那么第一个蓝色元素应该是第 25 个?然后是第 40、55 等

问题是,10n + 15 不会那样做。

10 * 1 + 15 = 25 // right
10 * 2 + 15 = 35 // wrong
10 * 3 + 15 = 45 // wrong

听起来你想要 15n + 10:

15 * 1 + 10 = 25 // right
15 * 2 + 10 = 40 // right
15 * 3 + 10 = 55 // right

所以实际的选择器是:

div:nth-child(15n + 10) {
    color: blue;
}

不幸的是,这也会选择第 10 个元素。我假设您希望 blue 在适用的情况下覆盖 red,除了不应匹配的第 10 个元素。所以你需要添加另一个选择器来重置第 10 个元素。

div:nth-child(10) {
    color: red;
}

这是一个 jsFiddle 演示:http://jsfiddle.net/mvdzc99b/

编辑

需求发生了变化,但我会保留原始信息以供引用。

要选择前 10 个中的所有,您可以使用 -n+10。然而,选择接下来的 15 个有点棘手。您需要使用从 11 到 25 的范围,这是通过组合 2 个 :nth-child() 选择器来完成的:

:nth-child(n+11):nth-child(-n+25) { ... }

接下来的 15 个将是

:nth-child(n+26):nth-child(-n+40) { ... }

你明白了。

jsFiddle:http://jsfiddle.net/mvdzc99b/3/

div {
    margin: 2px;
    width: 10px;
    height: 10px;
    background: black;
    float: left;
}

div:nth-child(-n+10) {
    background: red;
}

div:nth-child(n+11):nth-child(-n+25) {
    background: blue;
}

div:nth-child(n+26):nth-child(-n+40) {
    background: green;
}
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

关于css - 多个第 n 个子语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27936621/

相关文章:

Javascript 隐藏/显示切换在 Opera 中以两种方式工作,但在其他浏览器中只有一种方式

css - Stylus ParseError : expected “indent” , 得到 “;”

java - 如何使用 xpath 或 css 选择器提取标题属性和文本?

javascript - 寻找更快或更好的方法来使用 jquery 选择 XML 节点的第 n 个子节点

css - :first-child not being applied

html - 选择每个奇/偶 dt 元素,它在 dds 之后

css - 怎么实现css垂直和水平居中?

html - 使用 Div 的文本对齐问题

css - Internet Explorer 6 css 顺序很重要的错误

javascript - jQuery 是否在内部缓存元素?