:last-of-type 选择器对数据属性的行为
Behaviour of :last-of-type selector on data attribute
有人可以解释为什么 :first-of-type 和 :last-of-type 选择器的行为与它们在以下代码段中的行为相同吗?
https://codepen.io/anon/pen/jaxQNJ
HTML
<div class="container">
<h2 data-type data-type-a>A (should be black / is black)</h2>
<h2 data-type data-type-a>A (should be red / is black)</h2>
<h2 data-type data-type-b>B (should be green / is black)</h2>
<h2 data-type data-type-b>B (should be blue / is blue)</h2>
</div>
CSS
div{
color:black;
font-weight:bold;
}
.container h2[data-type]:last-of-type{
color:blue;
}
.container h2[data-type-a]:last-of-type{
color:red;
}
.container h2[data-type-b]:first-of-type{
color:green;
}
:last-of-type
和 :first-of-type
正在按预期工作:
The :last-of-type CSS pseudo-class represents the last element of its type among a group of sibling elements.
https://developer.mozilla.org/en-US/docs/Web/CSS/:last-of-type
问题是这个特定的选择器以h2
类型的最后一个元素为目标,忽略了你的属性选择器。因为 type 是 h2
而不是 data-type
或 data-type-a
.
我建议您使用 class
,它的意思是:
div {
color: black;
font-weight: bold;
}
.data-type-b {
color: green;
}
.data-type-a {
color: red;
}
.data-type:first-child {
color: inherit;
}
.data-type:last-child {
color: blue;
}
<div class="container">
<h2 class="data-type data-type-a">A (should be black / is black)</h2>
<h2 class="data-type data-type-a">A (should be red / is red)</h2>
<h2 class="data-type data-type-b">B (should be green / is green)</h2>
<h2 class="data-type data-type-b">B (should be blue / is blue)</h2>
</div>
有人可以解释为什么 :first-of-type 和 :last-of-type 选择器的行为与它们在以下代码段中的行为相同吗?
https://codepen.io/anon/pen/jaxQNJ
HTML
<div class="container">
<h2 data-type data-type-a>A (should be black / is black)</h2>
<h2 data-type data-type-a>A (should be red / is black)</h2>
<h2 data-type data-type-b>B (should be green / is black)</h2>
<h2 data-type data-type-b>B (should be blue / is blue)</h2>
</div>
CSS
div{
color:black;
font-weight:bold;
}
.container h2[data-type]:last-of-type{
color:blue;
}
.container h2[data-type-a]:last-of-type{
color:red;
}
.container h2[data-type-b]:first-of-type{
color:green;
}
:last-of-type
和 :first-of-type
正在按预期工作:
The :last-of-type CSS pseudo-class represents the last element of its type among a group of sibling elements.
https://developer.mozilla.org/en-US/docs/Web/CSS/:last-of-type
问题是这个特定的选择器以h2
类型的最后一个元素为目标,忽略了你的属性选择器。因为 type 是 h2
而不是 data-type
或 data-type-a
.
我建议您使用 class
,它的意思是:
div {
color: black;
font-weight: bold;
}
.data-type-b {
color: green;
}
.data-type-a {
color: red;
}
.data-type:first-child {
color: inherit;
}
.data-type:last-child {
color: blue;
}
<div class="container">
<h2 class="data-type data-type-a">A (should be black / is black)</h2>
<h2 class="data-type data-type-a">A (should be red / is red)</h2>
<h2 class="data-type data-type-b">B (should be green / is green)</h2>
<h2 class="data-type data-type-b">B (should be blue / is blue)</h2>
</div>