CSS :only-child

The :only-child CSS pseudo-class represents any element that is the only child of its parent.

Let's look at an example to understand how :only-child works:

Result:

    <div>
      <p>This paragraph is the only child of the div element</p>
    </div>
  

This paragraph is the only child of the div element

In the example above, the <p> element is the only child of the <div> element. We can target this element using the :only-child CSS pseudo-class.

Here is an example of how to style the <p> element using the :only-child pseudo-class:

Result:

    <style>
         div p:only-child {
                 color: blue;
          }
    </style>
    <div>
      <p>This paragraph is the only child of the div element</p>
    </div>
  

This paragraph is the only child of the div element

In the example above, the <p> element is styled with a blue color because it is the only child of the <div> element.

By using the :only-child CSS pseudo-class, you can target elements that are the only child of their parent and apply specific styles to them.