CSS - Pseudo-class :only-child



The CSS pseudo-class selector :only-child matches or represents an element that is the only child of its parent element or in other words, an element without any siblings. This pseudo-class behaves in the same manner as :first-child :last-child or :nth-child(1) :nth-last-child(1), but the specificity is low.

The element that is selected by this pseudo-class must have a parent.

Syntax

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

CSS :only-child() Example

Here is an example of :only-child pseudo-class, applied on <p> tag, under <div> parent element.

In this example, the CSS rules will only apply to the first <p> element found within the first <div> element, as that is the only parent with just one child element.

<html>
<head>
<style>
   .field {
      margin: 1px;
      padding: 1px;
   }

   p:only-child {
      color: darkblue;
      background-color: lightpink;
   }

   div {
      border: 2px solid black;
      width: 500px;
   }
</style>
</head>
<body>
      <div class="field">
         <p>Only child of this div</p>
      </div>
      
      <div class="field">
         <p>First Child</p>
         <p>Second Child</p>
      </div>

      <div class="field">
         <h1>Heading - first child </h1>
         <p>Only p child, but second child</p>
      </div>
</body>
</html>

Here is an example of :only-child pseudo-class, applied on <li> tag, under <ol> and <ul> parent elements.

In this example, the CSS rules will apply to the only <li> element found within an <ol> and <ul> element.

<html>
<head>
<style>
   .field {
      margin: 1px;
      padding: 1px;
   }

   li:only-child {
      color: darkblue;
      background-color: lightpink;
      padding: 5px;
   }

   div {
      border: 2px solid black;
      width: 500px;
   }
</style>
</head>
<body>
      <div class="field">
         <ol>Ordered list:
            <li>Only one item</li>
         </ol>
      </div>
      
      <div class="field">
         <ol>
            <li>One item</li>
            <li>Two item</li>
         </ol>
      </div>

      <div class="field">
         <ul>Unordered list:
            <li>First Item</li>
         </ul>
      </div>
</body>
</html>
Advertisements