表奇数偶数tr backgroundcolor在特定类上

时间:2019-05-02 16:01:02

标签: html css

我只想更改.headcol类的奇数tr的背景颜色。

.headcol是左侧的粘性列。

thead th {
  position: -webkit-sticky; /* for Safari */
  position: sticky;
  top: 0;
  font-family: Poppins-Thin, sans-serif;
}

.headcol {
  position: -webkit-sticky; /* for Safari */
  position: sticky;
  left: 0;
  background-color: white;
}

.headcol tr:nth-child(odd) {
  background-color: blue;
}
<table class="table" id="TabListing">
 <thead class="thead-dark">
   <th class="headcol">Nom</th>
   <th>Prénom</th>
 </thead>

<tbody>
 <tr>
  <td class="headcol">BAR</td>
  <td>Mohamed</td>
 </tr>
<tr>
 <td class="headcol">BIAI</td>
 <td>Ikrame</td>
 </tr>

</tbody>
</table>

这段代码没有给我任何东西...

如果我尝试:

tr:nth-child(odd) {
  background-color: blue;
}

奇数tr是蓝色,但不是.headcol

2 个答案:

答案 0 :(得分:0)

我为您输入了正确的代码

<!DOCTYPE html>
<html>
<head>
<style> 
thead th {
  position: -webkit-sticky; /* for Safari */
  position: sticky;
  top: 0;
  font-family: Poppins-Thin, sans-serif;
}

.headcol {
  position: -webkit-sticky; /* for Safari */
  position: sticky;
  left: 0;
  background-color: white;
}

tr:nth-child(odd) {
  background-color: blue;
}
</style>
</head>
<body>
<table class="table" id="TabListing">
 <thead class="thead-dark">
   <th class="headcol">Nom</th>
   <th>Prénom</th>
 </thead>

<tbody>
 <tr>
  <td class="headcol">BAR</td>
  <td>Mohamed</td>
 </tr>
 <tbody>
 <tr>
  <td class="headcol">BIAl</td>
  <td>Ikrame</td>
 </tr>

</tbody>
</table>

</body>
</html>

答案 1 :(得分:0)

所以你很亲近。但是请记住-假定左侧的选择器项包含右侧的选择器项(除非选择器中的某些特定运算符位于它们之间以更改关系)。所以这个:

.headcol tr:nth-child(odd) {
  background-color: blue;
}

...正在用类tr描述元素内的每个奇数.headcol,这永远不会反映在您的标记中。相反,您想在奇数.headcol内选择任何tr分类的元素,该元素为:

tr:nth-child(odd) .headcol {
  background-color: blue;
}

这是我在以下代码段中所做的,如果我正确理解它们的话,这些代码似乎符合您的要求。

thead th {
  position: -webkit-sticky; /* for Safari */
  position: sticky;
  top: 0;
  font-family: Poppins-Thin, sans-serif;
}

.headcol {
  position: -webkit-sticky; /* for Safari */
  position: sticky;
  left: 0;
  background-color: white;
}

tr:nth-child(odd) .headcol {
  background-color: blue;
}
<table class="table" id="TabListing">
    <thead class="thead-dark">
        <th class="headcol">Nom</th>
        <th>Prénom</th>
    </thead>
    <tbody>
        <tr>
            <td class="headcol">BAR</td>
            <td>Mohamed</td>
        </tr>
        <tr>
            <td class="headcol">BIAI</td>
            <td>Ikrame</td>
        </tr>
        <tr>
            <td class="headcol">BIAI</td>
            <td>Alex</td>
        </tr>
        <tr>
            <td class="headcol">BIAI</td>
            <td>Clement</td>
        </tr>
        <tr>
            <td class="headcol">BIAI</td>
            <td>Rachel</td>
        </tr>
    </tbody>
</table>