-->

Apply text color to html column

2019-02-25 21:24发布

问题:

<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>

I can't figure out for the life of me why Decimal is not in green!

I need the entire column to be in green font, background-color works for some reason.

Is there a way to do this without adding a class to every tr?

I need to be able to apply a different colour to each column.

回答1:

th is inside tr, hence its not taking the font color.

Here is my solution, Its Not a perfect solution, but will not have to add individual classes .

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>



回答2:

This will select the entire column as you mentioned:

<!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:

    <style>
th:first-of-type{color:red;}
</style>
<table>
  <colgroup>
    <col/>
    <col style="background-color:green" />
    <col class="char" />
  </colgroup>
  <tr>
    <th>
      Decimal
    </th>
    <th>
      Hex
    </th>
    <th>
      Char
    </th>
  </tr>
</table>


----------