Menu
Coddy logo textTech

最後の要素を選択する

CoddyのHTMLジャーニー「CSS Mastery」セクションの一部 — レッスン 14/43。

:last-child 擬似クラスは、親要素の最後の子である要素を選択します。

例えば:

<div class="parent">
  <p>First paragraph</p>
  <p>Middle paragraph</p>
  <p>Last paragraph</p>
</div>

最後の段落だけにスタイルを適用するには、:last-child 疑似クラスを使用します:

p:last-child {
  color: red;
  font-weight: bold;
}

このCSSを適用すると、親divの最後の要素(last child)であるため、「Last paragraph」だけが赤色で太字になります。

quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

challenge icon

チャレンジ

簡単

任意の段落グループ内の最後の <p> 要素をスタイリングするCSSルールを作成してください。

  1. 青色の背景色(#046ae0)whiteのテキストでスタイリングしてください。
  2. 最後の段落のフォントの太さ(font weight)boldに設定してください。

チートシート

:last-child 疑似クラスは、親要素の最後の子である要素を選択します。

p:last-child {
  color: red;
  font-weight: bold;
}

これにより、親コンテナ内の最後の段落要素のみがスタイリングされます。

自分で試してみよう

<!DOCTYPE html>
<html>
<head>
    <title>Targeting the Last Child</title>
  <style>
    /* Write your CSS rule here */

  </style>
</head>
<body>
    <div> 
        <h2>Exploring the Universe</h2>
        <p>The universe is vast, with countless stars and galaxies waiting to be discovered.</p>
        <p>New technologies allow us to explore deeper into space, revealing its many secrets.</p>
        <p>We continue to learn more about distant planets and the possibility of life beyond Earth.</p> 
    </div>
    <div>
        <h2>The Deep Ocean</h2>
        <p>Our oceans are mysterious, covering most of Earth, yet we know so little about them.</p>
        <p>Many species live in extreme conditions, some of which are still being discovered today.</p>
        <p>Exploring the ocean depths gives us insights into life at the planet's most remote locations.</p> 
    </div>
</body>
</html>
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

CSS Masteryのすべてのレッスン