Menu
Coddy logo textTech

Targeting the Last Child

Part of the CSS Mastery section of Coddy's HTML journey — lesson 14 of 43.

The :last-child pseudo-class selects elements that are the last child of their parent.

For example:

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

To style only the last paragraph, use the :last-child pseudo-class:

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

After applying this CSS, only "Last paragraph" will be red and bold because it's the last child of the parent div.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Create a CSS rule to style the last <p> element in any group of paragraphs.

  1. Style it with a blue background color (#046ae0) and white text.
  2. Set the font weight of the last paragraph to bold.

Cheat sheet

The :last-child pseudo-class selects elements that are the last child of their parent:

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

This will style only the last paragraph element within its parent container.

Try it yourself

<!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 iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in CSS Mastery