:only-child

:only-child – pseudo-class | Selectors Level 3

The :only-child selects element that is the only child of its parent.

Sytnax

element:only-child {
    style properties;
}

The :only-child selector is the same as :first-child:last-child or nth-child(1):nth-last-child(1). The :only-child has lower specificity.

Examples

The HTML code:

<div class="contain-1">
    <span>only child</span>
</div>
<p class="contain-2">
    <span>only child</span>
</p>
<div class="contain-3">
    <p>Paragraph - child 1</p>
    <span>Span - child 2</span>
</div>
<div class="contain-4">
    <p>only child</p>
</div>
:only-child{
    background:#FFB7C5;
}

It selects every element that is only child of its parent:

  • a span element in the div with class="contain-1"
  • a span element in the p with class="contain-2"
  • a p element in the div with class="contain-4"

 

span:only-child{
    background:#FFB7C5;
}

It selects every span> element that is only child of its parent:

  • a span element in the div with class="contain-1"
  • a span element in the p with class="contain-2"

 

div span:only-child{
    background:#FFB7C5;
}

It selects every span element that is only child of its parent div element:  a span element in the div with  class="contain-1"

Related

Resources

Posted in CSS

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.