如何从2开始选择每个第4个元素?

时间:2017-03-01 06:48:22

标签: html css css-selectors

如何从2, 6, 10, 14, 18, 22

等模式中选择元素

我尝试写这个(2+(n-1)4)但CSS只允许+-运算符?

.timeline__item-bg:nth-child(2+(n-1)4):before {
    content: '';
    left: 74%;
    top: 99%;
    z-index: -1;
    transform: rotate(4deg);
    background: #60a8e2 transition: all 1s ease-in-out;
}

2 个答案:

答案 0 :(得分:3)

将您的选择器更改为以下内容:

.timeline__item-bg:nth-child(4n+2):before {}

这是一个有效的例子:

.timeline__item-bg:nth-child(4n+2) {
    color: red;
}
<ul>
  <li class="timeline__item-bg">1</li>
  <li class="timeline__item-bg">2</li>
  <li class="timeline__item-bg">3</li>
  <li class="timeline__item-bg">4</li>
  <li class="timeline__item-bg">5</li>
  <li class="timeline__item-bg">6</li>
  <li class="timeline__item-bg">7</li>
  <li class="timeline__item-bg">8</li>
  <li class="timeline__item-bg">9</li>
  <li class="timeline__item-bg">10</li>
  <li class="timeline__item-bg">11</li>
  <li class="timeline__item-bg">12</li>
  <li class="timeline__item-bg">13</li>
  <li class="timeline__item-bg">14</li>
  <li class="timeline__item-bg">15</li>
  <li class="timeline__item-bg">16</li>
  <li class="timeline__item-bg">17</li>
  <li class="timeline__item-bg">18</li>
  <li class="timeline__item-bg">19</li>
  <li class="timeline__item-bg">20</li>
  <li class="timeline__item-bg">21</li>
  <li class="timeline__item-bg">22</li>
</ul>

答案 1 :(得分:0)

  • 要选择每个第4个元素,请使用:nth-child(4n)
  • 从第二个元素:nth-child(4n + 2)
  • 开始

工作考试:

ul li:nth-child(4n+2) {
  background: green;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
  <li>11</li>
  <li>12</li>
  <li>13</li>
  <li>14</li>
  <li>15</li>
  <li>16</li>
  <li>17</li>
  <li>18</li>
  <li>19</li>
  <li>20</li>
  <li>21</li>
  <li>22</li>
</ul>