Can I color table columns using CSS without coloring individual cells?

前端 未结 8 466
不思量自难忘°
不思量自难忘° 2020-12-12 13:07

Is there a way to color spans of columns all the way down. See, starting example below:

相关标签:
8条回答
  • 2020-12-12 14:09

    I would use the nth-child css pseudo-class for this:

    tr td:nth-child(2), tr th:nth-child(2), tr td:nth-child(3), tr td:nth-child(4), tr th:nth-child(4), tr td:nth-child(6), tr td:nth-child(7){
        background-color: #DDD;
    }
    

    tr td:nth-child(2),
    tr th:nth-child(2),
    tr td:nth-child(3),
    tr td:nth-child(4),
    tr th:nth-child(4),
    tr td:nth-child(6),
    tr td:nth-child(7) {
      background-color: #DDD;
    }
    <table border="1">
      <tr>
        <th>Motor</th>
        <th colspan="3">Engine</th>
        <th>Car</th>
        <th colspan="2">Body</th>
      </tr>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
      </tr>
      <tr>
        <td>7</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
      </tr>
    </table>

    0 讨论(0)
  • 2020-12-12 14:09

    This is an old question with a lot of great answers. Just wanted to add the -n and nth-last-child selectors that haven't yet been mentioned. They're helpful when applying CSS to multiple columns but may not know the number of columns prior to styling, or have multiple tables with varying widths.

    /* Select the first two */
    table tr td:nth-child(-n + 2) {
      background-color: lightblue;
    }
    
    /* Select all but the first two */
    table tr td:not(:nth-child(-n + 2)) {
        background-color:lightgreen;
    }
    
    /* Select last two only */
    table tr td:nth-last-child(-n + 2) {
      background-color:mistyrose;
    }
    
    /* Select all but the last two */
    table tr td:not(:nth-last-child(-n + 2)) {
        background-color:yellow;
    }
    

    jsFiddle: https://jsfiddle.net/3rpf5oht/2/

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