Behaviour of :last-of-type selector on data attribute

Viewed 1417

May someone explain why the :first-of-type and :last-of-type selectors behave like they do in the following snippet?

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

:last-of-type and :first-of-type are working as expected:

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

The problem is that this particular selector is targeting the last element of type h2, ignoring your attribute selector. Because the type is h2 and not data-type or data-type-a.

I'd recommend you to use class, it's what it's meant to:

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>

Related