: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

Browser compatibility

Internet Explorer
9.0
Firefox
1.5
Chrome
2
Safari
3.1
Opera
9.5
Mobile
Safari Mobile
3.1
Android
2.1
Chrome Mobile
works
IE Phone
works
Opera Mini
works
Opera Mobile
10.0