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

5
这听起来很简单,但我找不到关于它的许多帖子。基本上,我想要第一列红色,第二列绿色,第三列红色等等... 我该如何在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}

1
http://jsfiddle.net/TG8cd/? - underscore
重复的问题:http://stackoverflow.com/questions/19430005/add-alternate-background-style-to-odd-rows-of-html-table/19430053#19430053 - Paulie_D
请注意,目前没有任何答案适用于旧版浏览器。 - ediblecode
2个回答

7

为了表明存在,您需要添加一个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

你可以使用tr:nth-childMozilla文档。

例如:

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

4
列,不是行。 - danmc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接