nth-child:如何以两个为一组来选择元素 [英] nth-child: how to pick elements in groups of two

查看:200
本文介绍了nth-child:如何以两个为一组来选择元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的表:

Let's say I have a table like this:

 <div class="fc-slats">
  <table>
    <tbody>
      <tr>
        <td class="fc-widget-content fc-major">16</td>
        <td class="fc-widget-content fc-minor">16</td>
        <td class="fc-widget-content fc-major">17</td>
        <td class="fc-widget-content fc-major">17</td>
        <td class="fc-widget-content fc-major">18</td>
        <td class="fc-widget-content fc-minor">18</td>
      </tr>
    </tbody>
  </table>
  </div>

我希望第一和第二个单元格具有一种颜色,第三和第四个单元格具有另一种颜色,第五和第六个单元格具有第一种颜色...换句话说,这是旧的奇偶数交替的配色方案,但每组中有两个单元格.

And I want the first and second cells to have one color, the third and fourth cells to have another color, the fifth and sixth cells to have the the first color... In other words, it's the old odd-even alternating color scheme, except with two cells in each group.

我正在尝试使用CSS的nth-child选择器:

I am trying to do this with CSS's nth-child selector:

fc-slats td:nth-child(int(n/2)) {
  background-color: red;
}

但是我不知道如何精确地为第n个子"选择器编写公式.我想CSS不支持int等数学函数或if... then这样的条件函数,那么在那种情况下,我将如何实现呢?

But I don't know how exactly to write the formula for the "nth-child" selector. I suppose CSS doesn't support there math functions like int, or conditionals like if... then, so in that case, how would I achieve this?

为了简洁起见,我仅在此表中添加了6个单元格,但假定该表将具有任意长度;换句话说,我正在寻找一种通用"解决方案.

I just added 6 cells in this table for the sake of brevity, but assume that the table is going to have an arbitrary length; in other words, I'm looking for an "universal" solution.

推荐答案

您可以选择每四个td及其前一个与nth-child(4n)nth-child(4n - 1)相同的同级项:

You can select every fourth td along with its immediately preceding sibling with nth-child(4n) and nth-child(4n - 1):

td {
  background: blue;
}

td:nth-child(4n), td:nth-child(4n - 1) {
  background: red;
}

 <div class="fc-slats">
  <table>
    <tbody>
      <tr>
        <td class="fc-widget-content fc-major">16</td>
        <td class="fc-widget-content fc-minor">16</td>
        <td class="fc-widget-content fc-major">17</td>
        <td class="fc-widget-content fc-major">17</td>
        <td class="fc-widget-content fc-major">18</td>
        <td class="fc-widget-content fc-minor">18</td>
      </tr>
    </tbody>
  </table>
  </div>

这篇关于nth-child:如何以两个为一组来选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆