CSS Reference Pseudo-class


:only-child is a CSS pseudo-selector which matches an element if it is its parent’s only child. That is, the element is selected only if its parent has no other children of any type.

For example, li:only-child will match a list item only if it is the only item in the list. p:only-child will match a paragraph only if it is the only child inside its container. So, it will select the following paragraph:

        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Soluta, enim, libero voluptatum id nostrum porro laborum error nisi fugit atque a possimus ullam maxime quia tenetur obcaecati dolorum dolore placeat.

But it will not match the following paragraph, since it is not the only child of its parent:

        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, iusto, eos similique eaque minus magni tempore repudiandae mollitia dignissimos obcaecati animi quis et impedit consectetur optio modi perferendis voluptate corporis!

Trivia & Notes

The :only-child pseudo-class selector is the same as :first-child:last-child and :nth-child(1):nth-last-child(1), except that is has a lower specificity. :first-child:last-child will match an element which is the first and last child of its parent (i.e the only child), and :nth-child(1):nth-last-child(1) will match an element if it is the first child from the top and the first child from the bottom, which also means it is the only child of its parent.

Just like other pseudo-class selectors, the :only-child selector can be chained with other selectors such as :hover and with pseudo-elements such as ::after, among others. For example, the following rule will add content to an item in a list if it is the only item in that list:

li:only-child::after {
    content: "Last item, get it before it is sold out!";
    color: tomato;


The following are all valid :only-child declarations:

li:only-child { /* styles */}

span:only-child { /* styles */}

article:only-child:hover { /* styles */}

a:only-child::after { /* styles */}

.product:only-child h1 { /* styles */}

Live Demo

In the following demo, :only-child is used to style list items and links that are the only children of their parents, respectively.

View this demo on the Codrops Playground

Browser Support

The :only-child pseudo-class selector is supported in Chrome, Firefox, Safari, Opera 9.5+, Internet Explorer 9+, and on Android and iOS.

Written by

Last updated February 3, 2015 at 12:33 pm by Mary Lou

Do you have a suggestion, question or want to contribute? Submit an issue.