CSS Selector for nth range?

前端 未结 3 657
误落风尘
误落风尘 2020-12-01 01:15

How can I adapt the CSS selector below:

.myTableRow td:nth-child(?){
  background-color: #FFFFCC;
}

so it applies to td columns

相关标签:
3条回答
  • 2020-12-01 01:57

    If you want to select elements 2 through 4, here's how you can do it:

    td:nth-child(-n+4):nth-child(n+2) {
      background: #FFFFCC;
    }
    

    Remind that the selector chain sequence should be from greatest to least. Safari has a bug that prevents this technique from working.

    0 讨论(0)
  • 2020-12-01 02:03

    One more approach you could use is:

    .myTableRow td:nth-child(n+2):nth-child(-n+4){
        background-color: #FFFFCC;
    }
    

    This is a little clearer because it includes the numbers in your range (2 and 4) instead of having to count backwards from the end.

    It's also a bit more robust because you don't have to consider the total number of items there are.

    For clarification:

    :nth-child(n+X)     /* all children from the Xth position onward */
    :nth-child(-n+x)    /* all children up to the Xth position       */
    

    Example:

    #nn div {
        width: 40px;
        height: 40px;
        background-color: black;
        display: inline-block;
        margin-right: 10px;
    }
    
    #nn div:nth-child(n+3):nth-child(-n+6) {
        background-color: blue;
    }
    <div id="nn">
        <div></div>    
        <div></div>    
        <div></div>    
        <div></div>    
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
    </div>

    0 讨论(0)
  • 2020-12-01 02:08

    You won't be able to do this with a single :nth-child() — you'll need to chain at least one other such pseudo-class. For example, a combination of :nth-child() and :nth-last-child() (the n+2 bit means start counting forward and backward respectively from the 2nd child):

    .myTableRow td:nth-child(n+2):nth-last-child(n+2){
    background-color: #FFFFCC;
    }
    

    Alternatively, instead of making use of a formula, simply exclude :first-child and :last-child:

    .myTableRow td:not(:first-child):not(:last-child){
    background-color: #FFFFCC;
    }
    
    0 讨论(0)
提交回复
热议问题