如何在表格中交替列背景颜色?

时间:2013-10-24 10:31:08

标签: html css twitter-bootstrap

这听起来很简单,但我找不到很多关于它的帖子。

基本上我想要第一列红色,第二列绿色,第三红色等......

我怎样才能在css中执行此操作?

这是我的html代码(我正在使用bootstrap 3):

        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Welsh</th>
                    <th>English</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Shwmae <a href="#" onclick="playAudio('shwmae');"><span class="glyphicon glyphicon-volume-up play"></span></a></td>
                    <td>Hello</td>
                </tr>
                <tr>
                    <td>Bore da <a href="#" onclick="playAudio('boreda');"><span class="glyphicon glyphicon-volume-up play"></span></a></td>
                    <td>Good morning</td>
                </tr>
                <tr>
            </tbody>
        </table>

我尝试使用以下CSS,但它没有做任何事情:

col:first-child {background: #FF0}
col:nth-child(2n+3) {background: #CCC}

2 个答案:

答案 0 :(得分:5)

您需要通过添加colgroup

来指明存在

HTML

<table>
    <colgroup>
    <col>
    <col>
    <col>
  </colgroup>
  <tr>
    <th>Descrizione</th>
    <th>Convenzione</th>
    <th>Privato</th>
  </tr>

  <tr>
    <td>Tomografia computerizzata delle arcate dentarie</td>
    <td>€ 36,15</td>
    <td>€ 100,00</td>
  </tr>

  <tr>
    <td>Tomografia computerizzata delle arcate dentarie</td>
    <td>€ 36,15</td>
    <td>€ 100,00</td>
  </tr>

  <tr>
    <td>Tomografia computerizzata delle arcate dentarie</td>
    <td>€ 36,15</td>
    <td>€ 100,00</td>
  </tr>

  <tr>
    <td>Tomografia computerizzata delle arcate dentarie</td>
    <td>€ 36,15</td>
    <td>€ 100,00</td>
  </tr>
  <tr>
    <td>Tomografia computerizzata delle arcate dentarie</td>
    <td>€ 36,15</td>
    <td>€ 100,00</td>
  </tr>

  <tr>
    <td>Tomografia computerizzata delle arcate dentarie</td>
    <td>€ 36,15</td>
    <td>€ 100,00</td>
  </tr>  
</table>

CSS

col:nth-child(odd) {
  background:red;
}

col:nth-child(even) {
  background:green;
}

CODEPEN DEMO

答案 1 :(得分:0)

您将使用tr:nth-childMozilla Docs.

示例:

tbody tr:nth-child(2n+1) {
  ⋮ declarations
}
tbody tr:nth-child(odd) {
  ⋮ declarations
}