Last updated on

The :only-child pseudo-class selector property in CSS represents an element that has a parent element and whose parent element has no other element children. This would be the same as :first-child:last-child or :nth-child(1):nth-last-child(1), but with a lower specificity.

div p:only-child {
    color: red;
}

For example, if we nest paragraphs within a <div> like so…

<div>
  <p>This paragraph is the only child of its parent</p>
</div>
 
<div>
  <p>This paragraph is the first child of its parent</p>
  <p>This paragraph is the second child of its parent</p>
</div>

Now we can style the only <p> of our first child <div>. The subsequent <div> and it’s children will never be styled as the parent container holds more than one child (i.e. the p tags).

p:only-child {
  color:red;
}

We could also mixin additonal pseudo classes like this example that selects the first paragraph within our nested div and the only-child of div.contain.

<div class="contain">
  <div>
    <p>Hello World</p>
    <p>some more children</p>
  </div>
</div>
div.contain div:only-child :first-child {
  color: red;
}

:only-child won’t work as a selector if your parent element contains more than one child with an identical tag. For example…

<div class="contain">
  <div>
    <h1>Div Child 1</h1>
    <p>paragraph1</p>
    <p>paragraph2</p>
  </div>

  <div>
    <h1>Div Child 2</h1>
    <p>paragraph1</p>
    <p>paragraph2</p>
  </div>

  <div>
    <h1>Div Child 3</h1>
    <p>paragraph1</p>
    <p>paragraph2</p>
  </div>
</div>
div.contain div:only-child {
  color: red;
}

This will result in no divs inheriting the color red as the parent contains more than 1 child (the 3 unnamed divs).

Related Properties

 

Browser Support

Chrome Safari Firefox Opera IE Android iOS
Any Any Any Any IE9+ Any Any

Leave a Reply

Your email address will not be published. Required fields are marked *