我有6种颜色的序列:
红色
绿色
蓝
青色
品红
黄
而元素1为红色。
元素2是绿色......等等。
列表可以包含无限数量的项目,并且应保留颜色序列。
最简单的方法是使用nth-child(n%6),但我们知道nth-child没有模块运算符。
序列:
不会起作用,因为第8个元素是青色,但它应该是绿色。
偏移量不会起作用,因为它只适用于第一次出现。
这个问题可以解决吗?
答案 0 :(得分:3)
你可以这样做
nth-child(6n-5)
每6:6,从6-5 = 1 nth-child(6n-4)
每6:6,从6-4 = 2 nth-child(6n-0)
,从6-0 = 6开始(可以写成nth-child(6n)
)或者像这样(在这种情况下更新,可能更合适)
nth-child(6n+1)
,从1开始 nth-child(6n+2)
,从2开始 nth-child(6n+6)
每6:6,从6开始(可以写成nth-child(6n)
)
/* left div's */
.left div:nth-child(6n-5) {
background: red;
}
.left div:nth-child(6n-4) {
background: green;
}
.left div:nth-child(6n-3) {
background: blue;
}
.left div:nth-child(6n-2) {
background: cyan;
}
.left div:nth-child(6n-1) {
background: magenta;
}
.left div:nth-child(6n) {
background: yellow;
}
/* right div's */
.right div:nth-child(6n+1) {
background: red;
}
.right div:nth-child(6n+2) {
background: green;
}
.right div:nth-child(6n+3) {
background: blue;
}
.right div:nth-child(6n+4) {
background: cyan;
}
.right div:nth-child(6n+5) {
background: magenta;
}
.right div:nth-child(6n) {
background: yellow;
}
/* for this demo only */
div div:nth-child(6n) + div {
margin-top: 15px;
}
.left, .right {
display: inline-block;
width: 33%;
}
<div class="left">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
<div>12</div>
<div>13</div>
<div>14</div>
<div>15</div>
</div>
<div class="right">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
<div>12</div>
<div>13</div>
<div>14</div>
<div>15</div>
</div>
答案 1 :(得分:1)
but we know that there's no module operator for nth-child.
What makes you think :nth-child
has no modulus syntax?
If you want :nth-child(x)
, where x ∈ ℤa
and a ∈ ℕ
, then the syntax is
:nth-child(an + b)
where b ∈ ℤ
is any representative of x
such that b < a
.
As you can see in LGSon's answer, usually b
is chosen in one of these sets
{0, 1, …, a-1}
{-a, -a+1, …, -1}
{-a+1, …, -1, 0}
Note: In this answer, ℤa
means ℤ⧸aℤ
, that is, the integers modulo a
.