Joh*_*ohn 4 css css-selectors css3
谁能告诉我为什么我桌子的第二排没有灰色背景?
<!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>
Run Code Online (Sandbox Code Playgroud)
在first-of-type
选择上的类或ID标签或元素,而不是工作.所以在你的情况下,下面的选择器将设置每种类型的第一个元素,它也恰好具有class='phone'
.
.phone:first-of-type td {background:grey;}
Run Code Online (Sandbox Code Playgroud)
在你的代码中,没有第一个类型的元素具有class='phone'
.第一个tr
有class='email'
.
如果您的第一个tr
拥有,class='phone'
那么样式将被应用,如下面的代码片段所示.
.phone td {
background: blue;
color: white;
}
.phone:first-of-type td {
background: grey;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
对于您的情况,您可以尝试下面的CSS.这会将其父级具有灰色background
的所有内容设置为灰色,然后将其所有兄弟td
节点class='phone'
覆盖为蓝色.
根据您的选择,您可以使用相邻的同级选择器或通用同级选择器.一般兄弟姐妹选择器是最好的.
请注意,相邻的兄弟选择器不会处理复杂的情况,其中元素与元素之间具有其他类
class='phone'
.
.phone td {background:grey; color:white;}
.phone ~ .phone td { background: blue;}
Run Code Online (Sandbox Code Playgroud)
.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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)