CSS Solid

Pseudo-Class - :only-child

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

Example:

p:only-child {
  color: red;
}

Above example sets text color (red) to the P child element when child element count is one and P is the only child element under the parent element.

Example:

<head>
    <title> CSS pseudo-class selector - :only-child</title>
    <style>
        p:only-child {
            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>

</body>
</html>

Result:

In the above example,

  • First DIV (id="div1") element has only one child P element. So style is applied here.
  • Second DIV (id="div2") element has two child elements. So style is not applied here.
  • Third DIV (id="div3") element has only one child element but that child is not P element. So style is not applied.

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