使用css和html的表格单元格的背景颜色

时间:2015-07-14 00:48:42

标签: html css

我编写了一个表格,我希望它是这样的:偶数行和奇数行具有不同的颜色,第一行和第一行具有相同的颜色; 我使用colgroup为第一列着色,但它不起作用。

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Untitled Document</title>

    <style type="text/css">
        tr.odd{background-color:#f9f;}
        tr.even{background-color:#fcf;}
    </style>

</head>

<body>
    <table width="200" border="1">
        <colgroup span="1" style="background:purple;"></colgroup>

        <tr style="background:purple;">
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
        </tr>
        <tr class="odd">
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
        </tr>
        <tr class="even">
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
        </tr>
        <tr class="odd">
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
        </tr>
    </table>

</body>
</html>

2 个答案:

答案 0 :(得分:0)

也许这就是你想要的。

<强> CSS

table tr td:first-of-type {background-color: purple !important;}

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style type="text/css">
tr.odd{background-color:#f9f;}
tr.even{background-color:#fcf;}
table tr td:first-of-type {background-color: purple !important;}
</style>
</head>

<body>
<table width="200" border="1">
<colgroup span="1" style="background:purple;"></colgroup>

  <tr style="background:purple;">
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
  <tr class="odd">
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
  <tr class="even">
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
  <tr class="odd">
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table>

</body>
</html>

答案 1 :(得分:0)

你可以使用nth-child pseudoclass的偶数和奇数规则

tr:nth-child(even) {background: #FCF}
tr:nth-child(odd) {background: #F9F}

其次是:

td:first-of-type,
tr:first-of-type {background: purple}