CSS - Pseudo-class :last-child



The CSS pseudo-class selector :last-child represents the last element that is inside the containing element.

The pseudo-class :last-child is similar to :last-of-type, but the former is more specific and targets the very last child of the parent element, while latter matches the last occurrence of a specified element.

Syntax

:last-child {
    /* ... */
}

CSS :last-child Example

Following example demonstrates use of :last-child pseudo-class. In this example, the CSS rules will only apply to the last <p> element found within a <div> element, leaving other <p> elements within the same container unaffected.

<html>
<head>
<style>
   p:last-child {
      color: black;
      background: yellow;
      font-weight: 600;
      font-size: 1em;
      font-style: italic;
      padding: 5px;
   }
   div {
      border: 2px solid black;
      margin-bottom: 5px;
   }
</style>
</head>
<body>
   <div>Parent element
      <p>first child, so no change</p>
      <p>second/last child, so :last-child pseudo-class applied</p>
   </div>
   <div>Parent element
      <h2>h3 tag, so no change</h2>
      <p><p> tag, is the last child.</p>
   </div>
</body>
</html>

Following example demonstrates use of :last-child pseudo-class, applied on <li> tag, under <ul> parent element. In this example, the CSS rules will only apply to the last <li> element found within a <ul> element, leaving other <li> elements within the same container unaffected.

<html>
<head>
<style>
   ul li:last-child {
      color: black;
      background: peachpuff;
      font-weight: 600;
      font-size: 1em;
      font-style: italic;
      padding: 5px;
   }
   div {
      border: 2px solid black;
      margin-bottom: 5px;
      width: 300px;
   }
</style>
</head>
<body>
   <div>
      <ul>
         <li>One</li>
         <li>Two</li>
         <li>Three
      </ul>
   </div>
</body>
</html>
Advertisements