:last-of-type选择器对数据属性的行为

扎米

有人可以解释一下为什么: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预期工作:

:last-of-type CSS伪类表示一组同级元素中该类型最后一个元素。
https://developer.mozilla.org/zh-CN/docs/Web/CSS/:last-of-type

问题在于此特定选择器的目标是type最后一个元素h2,而忽略了属性选择器。因为类型h2and not data-typeor 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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章