CSSで最後の要素にだけスタイルを適用させない、疑似クラス「:not()」と「:last-of-type」の組み合わせは便利
Post on:2022年9月13日
疑似クラスを使いなせるようになると、CSSはより楽しくなります。
リストなど複数の兄弟要素を配置した時に、最後の要素にだけスタイルを適用しないようにするには、:not()
と:last-of-type
を組み合わせると便利です。
下記のように最後だけラインをつけないとか、margin
やpadding
を変えるという時によく使用されるCSSのテクニックです。

CSSの疑似クラス:not()
も:last-of-type
もすべてのブラウザ(IE含む)でサポートされています。

さらにいろいろな使い方については、以前の記事をご覧ください。
まずは、実際の動作をご確認ください。
リストのアイテム間に点線があり、最後のアイテムにだけ点線がありません。
See the Pen
border between list items by Joshua Comeau (@joshwcomeau)
on CodePen.
HTMLはシンプルです。
1 2 3 4 5 6 |
<ul> <li>The Long Way to a Small, Angry Planet</li> <li>Winter's Orbit</li> <li>Master of Formalities</li> <li>Screw The Galaxy: Hard Luck Hank</li> </ul> |
CSSもシンプルです。
:last-of-type
は最後の要素で、:not()
は一致しない要素。つまり、最後ではない要素にborder-bottom
のスタイルを適用します。
1 2 3 |
li:not(:last-of-type) { border-bottom: 4px dotted tomato; } |
こういった兄弟要素の最後(もしくは最初)だけにスタイルを適用する方法は、ほかにもあります。フクロウセレクタ(* + *
)を使用して定義することもできます。
1 2 3 |
* + * { border-top: 4px dotted tomato; } |
フクロウセレクタは、あるアイテムに続くすべてのアイテムを選択するセレクタです。
元ネタは下記ツイートより。
One of my favourite lil’ CSS selectors is “:not(:last-of-type)”.
For example, I'm using it here to apply a bottom border to each item *except* the last one, so that there's a border between each list item: pic.twitter.com/GaxuSaoUWB
— Josh W. Comeau (@JoshWComeau) September 1, 2022
sponsors