【问题标题】:How do I alternate column background colours in a table?如何在表格中交替列背景颜色?
【发布时间】:2013-10-24 18:51:21
【问题描述】:

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

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

如何在 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}

【问题讨论】:

标签: html css twitter-bootstrap


【解决方案1】:

您需要通过添加一个 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

【讨论】:

    【解决方案2】:

    您将使用tr:nth-childMozilla Docs.

    例子:

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

    【讨论】:

    • 列,而不是行。
    猜你喜欢
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 2022-08-08
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 2014-06-17
    相关资源
    最近更新 更多