nth-child: how to pick elements in groups of two

2019-08-18 22:55发布

问题:

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.

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

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

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?

EDIT: 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.

回答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>



回答2:

td {
    background: blue;
}

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

https://jsfiddle.net/2nLtgd9z/

It has already been answered on StackOverflow, do your research first: nth-child to alternate by 2 rows