CSS - Pseudo-class :only-of-type



The CSS pseudo-class selector :only-of-type matches or represents an element that has no siblings of same type, in the same parent container.

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

Syntax

:only-of-type {
   /* ... */ 
}

CSS :only-of-type Example

Here is an example of :only-of-type pseudo-class, applied on <p> and <h2> tags, under <div> parent element:

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

   p:only-of-type {
      color: darkblue;
      background-color: lightpink;
      padding: 5px;
   }

   h2:only-of-type {
      text-decoration-line: underline;
      color: green;
   }

   div {
      border: 2px solid black;
      width: 500px;
   }
</style>
</head>
<body>
   <div class="field">
      <h2>Heading 2 - only type</h2>
      <p>Paragraph tag - only type</p>
   </div>
   
   <div class="field">
      <h2>Heading 2 - only type</h2>
      <p>Paragraph tag 1 - we are two</p>
      <p>Paragraph tag 2 - we are two</p>
   </div>
</body>
</html>

In this example, the CSS rules will only apply to the only <p> and <h2> type elements found in the <div> parent container. The second <div> has only one <h2> type element, but two <p> elements, hence the style was applied only on <h2> element and not on <p> elements.

Advertisements