LoginSignup
1
0

特定のclassを持つ最後の要素

Posted at

以前は出来なかった特定のclassを持つ最後の要素への装飾。
それが今なら :has() を使って実現できるなと気づいたのでメモ。

これまで

これまで最後の要素への装飾で使われてきたのは :last-child:last-of-type の2種類かと思います。

:last-child

文字通り最後の要素。

The :last-child CSS pseudo-class represents the last element among a group of sibling elements.

MDN にこうある通り、兄弟要素の中の最後の要素を指定できます。
以前は親がある要素という縛りがありましたがSelectors Level 4からそれもなくなった様です。(Safariは未対応。執筆時点)

:last-of-type

こちらはタグの種類の中での最後の要素。

The :last-of-type CSS pseudo-class represents the last element of its type among a group of sibling elements.

MDN にこうある通り、兄弟要素の中でタグの種類ごとに分けたグループの中の最後の要素を指定できます。

class名を起点にした選択はできなかった

これまでは上記2つしかなかったので、特定のclassを持った中の最後の要素という指定はできなかった。
それほどの頻度ではなかったが指定したい場面には何度か遭遇したことがあり、地味に困った記憶だけがある。

現在

:last-child や :last-of-type のように直接選択できる擬似クラスが登場したわけではないが、なんとも便利な :has 擬似クラス関数が登場したことで、特定のclass名を持つ最後の要素という指定も可能になった。

<div class="has">
  <div class="start">div.start</div>
  <div class="item">div.item</div>
  <div class="item">div.item</div>
  <div class="item">div.item</div>
  <div class="end">div.end</div>
</div>

例えばこういったHTMLがあった場合、最後の div.item を指定するにはどうしたらいいか。

.item:not(:has(~ .item)) { ... }

こういう形で、「以降の兄弟要素に指定したいclassを持たない」という指定をしてあげることで選択することができる。

以下実際の表示になります。

See the Pen Last element with :last-child, :last-of-type and :has by Masato Saito (@forty4_jp) on CodePen.

has() がほとんどのブラウザで使える様になり、以前は出来なかったことがいろいろできる様になりましたね。

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0