CSS :only-child Pseudo Class

The :only-child pseudo-selector matches an element if it is the only child of its parent.

The element is selected only if its parent has no other children of any type.

Version

CSS3

Syntax

:only-child {
css declarations;
}

Example

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style> 
      p:only-child {
      background: #1c87c9;
      }
    </style>
  </head>
  <body>
    <h2>:only-child selector example</h2>
    <div>
      <p>Lorem ipsum is simply dumnmy text.</p>
    </div>
    <div>
      <p>Lorem ipsum is simply dummy text.</p>
      <p>Lorem ipsum is simply dummy text.</p>
    </div>
  </body>
</html>

Practice Your Knowledge

The :only-child pseudo-selector matches an element




Related articles