:last-child

The :last-child pseudo-class in CSS targets the last child element of its parent. You can use it to apply styles to the last element in a group of sibling elements.

Purpose

  • Targets the last element within a specific parent container.
  • Applies styles to the final element in a group of elements.

Syntax

selector:last-child {
  /* Styles to apply to the last child */
}

Example

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
ul li:last-child {
  background-color: yellow;
}

In this example, the styles defined within the ul li:last-child selector will only be applied to the last list item, which is “Item 3”.

Key Points

  • The :last-child pseudo-class is relative to the parent element.
  • It targets the last element among all siblings within the same parent.
  • It can be combined with other selectors to create more specific styles.

Additional Considerations

  • If you want to target the last element within a group of elements that have the same class or ID, you can use the :last-of-type pseudo-class.
  • For more complex scenarios, you might consider using JavaScript to dynamically identify and style the last child element.

Example with :last-of-type

<ul>
  <li class="item">Item 1</li>
  <li class="item">Item 2</li>
  <li class="item">Item 3</li>
</ul>
ul .item:last-of-type {
  background-color: yellow;
}

In this example, the styles will only be applied to the last list item that has the class “item”.