Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

CSS Dictionary

  1. Home
  2. CSS Dictionary
  3. [CSS Selector] E:only-child

[CSS Selector] E:only-child

Using 'selector:only-child', you can apply styles when the element is the only child element. This is generally called a 'pseudo-class'. Equivalent to ':first-child:last-child' or ':nth-child(1):nth-last-child(1)', but has lower specificity (priority) than those. Does not work in IE8 and below.

Sample Code

div p:only-child { color: red;} /* Makes the p element inside a div element red if it is the only child. */
div.hoge :only-child { color: blue;} /* Makes the child element blue if the div element with class name 'hoge' has only one child. */

Browser Display Result

div p:only-child { color: red;} /* Makes the p element inside a div element red if it is the only child. */
div.hoge :only-child { color: blue;} /* Makes the child element blue if the div element with class name 'hoge' has only one child. */

<div>
	<p>This is a p element.</p>
</div>
<div class="hoge">
	<div>This is a div element.</div>
</div>
<div>
	<p>This is a p element.</p>
	<div>This is a div element.</div>
</div>

Note that when combining id names, class names, or attributes with ':only-child', the browser first checks whether the element is the only child, and then checks whether it matches the specified element name, id name, class name, or attributes. For example, 'p.hoge:only-child' applies only when the sole child element is a p element AND it has the class name 'hoge'.

div p.hoge:only-child { color: red;} /* Makes the element red only if the p element inside a div is the sole child AND has the class name 'hoge'. */

<div>
	<p class="hoge">This is a p element with class name 'hoge' inside a div element.</p>
</div>
<div>
	<p>This is a p element inside a div element.</p>
</div>

Browser Compatibility

Chrome Chrome
2+
1 and earlier ×
Firefox Firefox
1.5+
Safari Safari
3.1+
2 and earlier ×
Edge Edge
12+
Supported in all versions
IE IE
11
10
9
8 ×
7 ×
6 ×
Opera Opera
9.5+
8 and earlier ×
iOS Safari iOS Safari
2+
1 and earlier ×
Android Android Browser
4.4+
3 and earlier ×
Chrome Android Chrome Android
Latest
Same support as desktop
Firefox Android Firefox Android
Latest
Same support as desktop

※ Version data is based on MDN.

If you find any errors or copyright issues, please .