【CSS/Sass】最後の子要素にスタイルを適用するlast-childの使い方

公開日:
2023/05/29
/
更新日:
2023/05/29
目次
CSSで、最後の子要素にスタイルを適用するlast-childの使い方をご紹介します。
最後の子要素にスタイルを適用するlast-childの使い方
CSSの擬似クラス:last-child
を使うことで、並列する要素のうち、最後の子要素にのみスタイルを適用できます。
具体的な使い方は以下のとおりです。
<!DOCTYPE html>
<html>
<head>
<style>
li:last-child {
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<ul>
<li>項目1</li>
<li>項目2</li>
<li>項目3</li>
</ul>
<div>
<p>段落1</p>
<p>段落2</p>
<p>段落3</p>
<p>段落4</p>
</div>
<ol>
<li>番号1</li>
<li>番号2</li>
<li>番号3</li>
<li>番号4</li>
<li>番号5</li>
</ol>
</body>
</html>
このソースをブラウザで表示させると、以下のようになります。

上のサンプルでは、li:last-child
としているため、リストの最後の要素のみ太赤字が適用されています。
last-childをネストして使用する
もう少し複雑な例を見てみましょう。
last-child
の中に、さらにlast-child
をあてました。
<!DOCTYPE html>
<html>
<head>
<style>
.container:last-child .nested:last-child {
background-color: yellow;
color: blue;
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<p>親要素1</p>
<div class="nested">
<p>ネストされた要素1</p>
<p>ネストされた要素2</p>
</div>
<div class="nested">
<p>ネストされた要素3</p>
<p>ネストされた要素4</p>
</div>
</div>
<div class="container">
<p>親要素2</p>
<div class="nested">
<p>ネストされた要素5</p>
<p>ネストされた要素6</p>
<p>ネストされた要素7</p>
</div>
<div class="nested">
<p>ネストされた要素8</p>
</div>
</div>
</body>
</html>
ブラウザで表示させると以下のようになります。

このケースでは、.container:last-child .nested:last-child
というCSSを用意しています。
最後のcontainerクラスに含まれる、最後のnestedクラスにのみ、スタイルが適用されていますね。
Sassでのlast-childの使い方
Sassでも、もちろん:last-child
が使えます。
ul {
li:last-child {
color: red;
font-weight: bold;
}
}
もしくは、以下のように&
でネストしても使えます。
ul {
li {
&:last-child {
color: red;
font-weight: bold;
}
}
}