CSS:第一个类型不工作

时间:2015-04-19 14:08:14

标签: css css3 css-selectors

有谁能告诉我为什么我桌子的第二排没有灰色背景?

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

2 个答案:

答案 0 :(得分:6)

first-of-type选择器适用于标记或元素,而不适用于类或ID。因此,在您的情况下,下面的选择器将设置每个类型的第一个元素,它也恰好具有class='phone'

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

在您的代码中,第一个类型的元素都没有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。这会将其父级background的所有td的{​​{1}}设置为灰色,然后将其所有兄弟的颜色覆盖为蓝色。

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

  

请注意,相邻的兄弟选择器不会处理复杂的情况,在这些情况下,元素与class='phone'元素之间具有其他类。

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

答案 1 :(得分:0)

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

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