CSS :last-child property


The :last-child pseudo-class in CSS targets the last child element of a specified parent element. It allows you to apply styles specifically to the last child, regardless of its type. This is useful for styling elements differently based on their position within a container.

Syntax

parent-selector:last-child { /* styles */ }
  • parent-selector: The selector targets the parent element.
  • :last-child: The pseudo-class applies styles to the last child of the parent element.

How It Works

  1. Basic Usage:

    • You use :last-child to apply styles to the last child element of a parent container.
    ul li:last-child { font-style: italic; }
    • In this example, the last <li> element within each <ul> will be styled with italic text.
  2. Compatibility:

    • The :last-child pseudo-class works with any type of element. It’s not limited to specific tags and applies based on the element's position as the last child of its parent.

Example

HTML

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Last Child Example</title> <style> ul li:last-child { color: green; font-weight: bold; } ol li:last-child { color: red; font-style: italic; } </style> </head> <body> <ul> <li>First item (ul)</li> <li>Second item (ul)</li> <li>Last item (ul)</li> </ul> <ol> <li>First item (ol)</li> <li>Second item (ol)</li> <li>Last item (ol)</li> </ol> </body> </html>

Explanation:

  • ul li:last-child:

    • Targets the last <li> element within each <ul>. This last list item is styled with green text and bold font weight.
  • ol li:last-child:

    • Targets the last <li> element within each <ol>. This last list item is styled with red text and italic font style.

Important Points

  1. Type of Last Child:

    • :last-child applies only if the element is the very last child of its parent. If the parent has other non-element nodes (like text nodes or comments) after the target element, :last-child will not apply.
    <div> <p>This paragraph is the last child.</p> <!-- A comment --> </div>
    div p:last-child { color: blue; }
    • In this case, the :last-child pseudo-class will apply to <p>, because it is the last element within the <div>, even though a comment follows.
  2. Combination with Other Selectors:

    • :last-child can be combined with other pseudo-classes and selectors for more specific styling.
    ul > li:last-child { color: green; }
    • This example targets only <li> elements that are the direct children of a <ul> and are the last child.
  3. Use in Nested Structures:

    • In nested structures, :last-child will only apply to the very last child of each parent element.
    div > p:last-child { color: red; }
    • This targets <p> elements that are the last child of their parent <div>, but not <p> elements that might be deeper in the structure.