CSS Solid

Pseudo-Class - :only-of-type

Selects a specified child element if it is the only child element of its type under the parent element.

Example:

p:only-of-type {
  color: red;
}

Above example sets text color (red) to the P child element based on its type when P type child element count is one under the parent element.

Example:

<!DOCTYPE html>

<html>
<head>
    <title> CSS pseudo-class selector - :only-of-type</title>
    <style>
        p:only-of-type {
            color: red;
        }

        div {
            border: 1px solid red;
            padding: 20px;
            width: 500px;
        }
    </style>
</head>
<body>
    <div id="div1">
        <p>1) P child element of the Parent element (DIV id="div1")</p>
    </div>

    <div id="div2">
        <p> 1) P child element of the Parent element (DIV id="div2")</p>
        <span>2) SPAN child element of the Parent element (DIV id="div2")</span>
    </div>

    <div id="div3">
        <span>1) SPAN child element of the Parent element (DIV id="div3")</span>
    </div>

    <div id="div4">
        <p> 1) P child element of the Parent element (DIV id="div4")</p>
        <p> 2) P child element of the Parent element (DIV id="div4")</p>
    </div>

</body>
</html>

Result:

In the above example,

  • First DIV (id="div1") element has only one P type child element. So style is applied here.
  • Second DIV (id="div2") element has two child elements. But only one P type element is available. So style is applied here.
  • Third DIV (id="div3") element has only one child element but that child (SPAN) element type is different. So style is not applied.
  • Fourth DIV (id="div4") element has two P type based child elements. So style is not applied here.

Using following Document Object Model (DOM) tree, above example is explained.