将文本颜色应用于HTML列

时间:2018-07-21 13:05:28

标签: html css html-table col

<table>
    <colgroup>
        <col style="color: green"/>
        <col style="background-color:green"/>
        <col class="char"/>
    </colgroup>
    <tr>
        <th>
            Decimal
        </th>
        <th>
            Hex
        </th>
        <th>
            Char
        </th>
    </tr>
</table>

我无法弄清楚为什么Decimal不是绿色的!

我需要整列为绿色字体,出于某些原因,背景颜色才起作用。

有没有一种方法可以不向每个tr添加类?

我需要能够为每列应用不同的颜色。

4 个答案:

答案 0 :(得分:2)

th在tr内,因此它没有采用字体颜色。

这是我的解决方案,它不是完美的解决方案,但不必添加单个类。

th:first-child {
  color: green;
}

th:nth-child(2) {
  color: yellow;
}
<table>
  <colgroup>
    <col style="color: green" />
    <col style="background-color:green" />
    <col class="char" />
  </colgroup>
  <tr>
    <th>
      Decimal
    </th>
    <th>
      Hex
    </th>
    <th>
      Char
    </th>
  </tr>
</table>

答案 1 :(得分:1)

  

我不知道为什么我的一生中Decimal不会变成绿色!

因为样式规则的一小部分在应用于col元素时没有任何作用。

CSS 2.1规范says ...

  

17.3列

     

表单元格可能属于两个上下文:行和列。但是,在源文档中,单元格是行的后代,而不是列的后代。但是,通过设置列的属性可以影响单元格的某些方面。

     

以下属性适用于列和列组元素:

     “边界”      

仅当在表格元素上将'border-collapse'设置为'collapse'时,各种边框属性才适用于列。在这种情况下,将在列和列组上设置的边界输入到冲突解决算法中,该算法将选择每个单元格边缘的边界样式。

     “背景”      

background属性为列中的单元格设置背景,但前提是单元格和行均具有透明背景。请参阅“表格层和透明度”。

     “宽度”      

'width'属性给出了列的最小宽度。

     “可见性”      

如果将列的“可见性”设置为“折叠”,则不会呈现该列中的任何单元格,并且会剪切跨入其他列的单元格。此外,表格的宽度将减少该列将占用的宽度。请参阅下面的“动态效果”。其他“可见性”值无效。

请注意,上面的列表中没有“颜色” 。它不适用于col元素,也不能以您尝试使用的方式使用。

不过,正如其他人所指出的那样,通常*足以为您的第 n 个表列设置样式的替代策略是使用:nth-child(或:first-child或{{ 3}})伪类来定位该列中的单元格:

th:first-child, td:first-child {
    color: blue;
    background: pink;
}
th:nth-child(2), td:nth-child(2) {
    color: white;
    background: green;
}
th:last-child, td:last-child {
    font-weight: bold;
    background: orange;
}
<table>
    <tr>
        <th>Blue on pink</th>
        <th>White on green</th>
        <th>Bold on orange</th>
    </tr>
    <tr>
        <td>Foo</td>
        <td>Bar</td>
        <td>Baz</td>
    </tr>
    <tr>
        <td>One</td>
        <td>Two</td>
        <td>Three</td>
    </tr>
</table>

*(仅“通常”使用,因为如果您尝试设置在某些td上使用:last-child属性的表的样式,以使其跨多个列,则此方法将无效。 )

答案 2 :(得分:-1)

这将选择您提到的整个列:

<!DOCTYPE html>
<html>
<head>
    <style>
        tr > th:first-child, td:first-child {
            color: green;
        }
    </style>
</head>
<body>
    <table>
        <colgroup>
            <col style="color: green"/>
            <col style="background-color:green"/>
            <col class="char"/>
        </colgroup>
        <tr>
            <th>
                Decimal
            </th>
            <th>
                Hex
            </th>
            <th>
                Char
            </th>
        </tr>
        <tr>
            <td>
                3244.21
            </td>
            <td>
                #8217
            </td>
            <td>
                c
            </td>
        </tr>
    </table>
</body>

答案 3 :(得分:-1)

--no-sandbox