CSS : first-of-type 不工作

CSS :first-of-type isn't working

谁能告诉我为什么我的 table 第二行没有灰色背景?

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.phone td {background:blue; color:white;}
.phone:first-of-type td {background:grey;}
</style>
</head>
<body>
<table>
<tbody>
    <tr class="email"><td>Row</td></tr>
    <tr class="phone"><td>Row</td></tr>
    <tr class="phone"><td>Row</td></tr>
</tbody>
</table>
</body>
</html>

first-of-type 选择器作用于标签或元素,而不作用于 类 或 id。因此,在您的情况下,下面的选择器将为每种类型的第一个元素的 <td> 子元素设置样式,该元素也恰好具有 class='phone'.

.phone:first-of-type td {background:grey;}

在您的代码中,第一个类型的元素 none 具有 class='phone'。第一个 trclass='email'.

如果您的第一个 tr 具有 class='phone',那么将应用该样式,如下面的代码片段所示。

.phone td {
  background: blue;
  color: white;
}
.phone:first-of-type td {
  background: grey;
}
<table>
  <tr class="email"> <!-- will not be styled because it doesn't have phone class-->
    <td>Row</td>
  </tr>
  <tr class="phone"> <!-- will not be styled either because it is not first tr -->
    <td>Row</td>
  </tr>
  <tr class="phone">
    <td>Row</td>
  </tr>
</table>

<table>
  <tr class="phone"> <!-- will be styled because it is first tr and has phone class-->
    <td>Row</td>
  </tr>
  <tr class="phone">
    <td>Row</td>
  </tr>
  <tr class="phone">
    <td>Row</td>
  </tr>
</table>


对于您的情况,您可以尝试以下 CSS。这会将其父项具有 class='phone' 的所有 tdbackground 设置为灰色,然后将其所有兄弟项覆盖为蓝色。

您可以根据自己的选择使用相邻同级选择器或通用同级选择器。 General Sibling 选择器是最好的。

Note that the adjacent sibling selector won't work complex cases where you have elements with other classes in between elements with class='phone'.

.phone td {background:grey; color:white;}
.phone ~ .phone td { background: blue;}

.phone td {
  background: grey;
  color: white;
}
.phone ~ .phone td {
  background: blue;
}

/* Adding below just to show the difference between the two selectors */
.phone + .phone td {
  color: gold;
}
<table>
  <tr class="email">
    <td>Row</td>
  </tr>
  <tr class="phone">
    <td>Row</td>
  </tr>
  <tr class="email">
    <td>Row</td>
  </tr>
  <tr class="phone">
    <td>Row</td>
  </tr>
  <tr class="phone">
    <td>Row</td>
  </tr>
  <tr class="phone">
    <td>Row</td>
  </tr>  
</table>
<hr>
<table>
  <tr class="phone">
    <td>Row</td>
  </tr>
  <tr class="email">
    <td>Row</td>
  </tr>
  <tr class="phone">
    <td>Row</td>
  </tr>
  <tr class="phone">
    <td>Row</td>
  </tr>
</table>

:first-of-type 查找元素(在兄弟列表中),而不是复杂的选择器。在这里,您的 .phone 元素都不是第一个兄弟 - .email 是。

据我所知,如果不更改 HTML 布局,就无法在纯 CSS 中执行此操作。