CSS :only-child Selector

❮ Previous Selectors Next ❯


/* sets the p element background to red if the p element is the only child of its parent */
p:only-child {
  background: red;


The :only-child selector selects an element if it’s the only child of its parent.

This is the same as :first-child, :last-child or :nth-child(n) :nth-last-child(n), but with a lower specificity.

Note: As originally defined, the selected element had to have a parent. Beginning with Selectors Level 4, this is no longer required.

Version: CSS3

Standard Syntax

:only-child {
  css declarations;

Browser Support

The numbers in the table specify the first browser version that fully supports the property.


More Example


/* sets the div border to red if the div is the only child of its parent */
div:only-child {
  color: red;
  border: 1px solid red;
❮ Previous Selectors Next ❯