totn CSS

CSS :only-child selector

This CSS tutorial explains how to use the CSS selector called :only-child with syntax and examples.

Description

The CSS :only-child selector allows you to target an element that is the only child element within its parent.

Syntax

The syntax for :only-child CSS selector is:

element:only-child { style_properties }

Parameters or Arguments

element
The only child of that type of element within its parent.
style_properties
The CSS styles to apply to the only child element.

Note

Browser Compatibility

The CSS :only-child selector has basic support with the following browsers:

  • Chrome
  • Android
  • Firefox (Gecko)
  • Firefox Mobile (Gecko)
  • Internet Explorer 9+ (IE 9+)
  • IE Phone 9+
  • Opera 9.5+
  • Opera Mobile 10+
  • Safari (WebKit)
  • Safari Mobile

Example

We will discuss the :only-child selector below, exploring examples of how to use this selector in CSS to apply styling to the only child element.

With <span> tag

Let's look at a CSS :only-child example where we apply the :only-child selector to a <span> tag.

The CSS would look like this:

span:only-child { color: red; font-size: 22px; }

The HTML would look like this:

<div>
  <p>Here are 2 sites <span>techonthenet.com</span> and <span>checkyourmath.com</span>.</p>
  <p>Here is only 1 site <span>bigactivities.com</span>.</p>
</div>

The result would look like this (The :only-child selector would style the <span> tags as follows):

CSS

In this CSS :only-child example, the first <p> tag contains more than one <span> tag, so those <span> tags are not styled by the :only-child selector. The second <p> tag contains only one <span> tag, so it will be styled by the :only-child selector. The color of the text within that span tag <span>bigactivities.com</span> will be displayed as large red font.

With <p> tag

Let's look at a CSS :only-child example where we apply the :only-child selector to a <p> tag.

The CSS would look like this:

p:only-child { background: yellow; }

The HTML would look like this:

<div>
  <p>TechOnTheNet.com has been providing helpful references, how-to's and FAQs since 2003. We focus on technologies such as Microsoft Access, Microsoft Excel, Microsoft Word, SQL, Oracle/PLSQL, MySQL, HTML, CSS, and the C Language.</p>
</div>
<div>
  <p>The information presented here is suitable for all programmers from beginner to expert.</p>
  <p>We hope you find this information useful and return to our site, as we expand our information base.</p>
</div>

The result would look like this (The :only_child selector would style the <p> tags as follows):

CSS

In this CSS :only-child example, the first <div> tag contains only one <p> tag so it will be styled by the :only-child selector making the background color within <p>This is the only paragraph in this div</p> display as yellow. The second <div> tag contains more than one <p> tag, so those <p> tags are not styled by the :only-child selector.