nth-child with mod (or modulo) operator

后端 未结 5 1685
忘了有多久
忘了有多久 2020-12-16 13:10

Is it possible to use the nth-child with modulo? I know you can specify a formula, such as

nth-child(4n+2)

But I can\'t seem t

相关标签:
5条回答
  • 2020-12-16 13:15

    I know this topic is very old, but here's the answer:

        .parent :nth-child(4n):nth-last-child(2) ~ *,
        .parent :nth-child(4n):nth-last-child(3) ~ *,
        .parent :nth-child(4n):nth-last-child(4) ~ * {
            color: gold;
        }
    

    This selector targets all children who are after the last child in the last full set of grouped children denoted by your nth-child formula.

    0 讨论(0)
  • 2020-12-16 13:24

    No, :nth-child() only supports addition, subtraction and coefficient multiplication.

    I gather you're trying to pick up the first 6 elements (as n mod 7 for any positive integer n only gives you 0 to 6). For that, you can use this formula instead:

    :nth-child(-n+6)
    

    By negating n, element counting is done backwards starting from zero, so these elements will be selected:

     0 + 6 = 6
    -1 + 6 = 5
    -2 + 6 = 4
    -3 + 6 = 3
    -4 + 6 = 2
    -5 + 6 = 1
    ...
    

    jsFiddle demo

    0 讨论(0)
  • 2020-12-16 13:26

    If you want to use nth-child with modulo k, just specify:

    nth-child(kn)
    

    For example, if you want to specify style for 3, 6, 9, .. elements, just specify (k = 3), and use:

    nth-child(3n)
    

    You can also specify an offset:

    nth-child(kn+offset)
    
    0 讨论(0)
  • 2020-12-16 13:28

    If you want modulous with n=2 than you can use even or odd.

    tr:nth-child(even) {
      background-color: #ffffdffffd;
    }
    
    0 讨论(0)
  • 2020-12-16 13:36

    I know this topic is very old, but here's the answer that's close enought to modulo operator:

    :not(:nth-child(7n))
    

    This will select elements 1-6, 8-13 and so on...

    :nth-child(an)
    

    The code above will select elements divisible by "a" so adding :not() selector forces CSS to select elements not divisible by "a".

    I hope someone find it useful ;)

    0 讨论(0)
提交回复
热议问题