CSS - :only-child
The :only-child
CSS pseudo-class represents any element which is the only child of its parent. This is the same as :first-child:last-child
or :nth-child(1):nth-last-child(1)
, but with a lower specificity.
Examples
Basic example
CSS
Copy Code
span:only-child { color: red; }
HTML
Copy Code
<div> <span>This span is the only child of its father</span> </div> <div> <span>This span is one of the two children of its father</span> <span>This span is one of the two children of its father</span> </div>
Result
A list example
CSS
Copy Code
li li { list-style-type: disc; } li:only-child { color: #6699ff; font-style: italic; list-style-type: square; }
HTML
Copy Code
<ol> <li>First <ul> <li>This is only child element </ul> </li> <li>Second <ul> <li>This list has two elements <li>This list has two elements </ul> </li> <li>Third <ul> <li>This list has three elements <li>This list has three elements <li>This list has three elements </ul> </li> <ol>
Result
Syntax
CSS
Copy Code
:only-child <a href="css/value_definition_syntax#curly_braces_(.7b_.7d)" title="Curly braces">{</a> <var>style properties</var> <a href="css/value_definition_syntax#curly_braces_(.7b_.7d)" title="Curly braces">}</a>
Description
The :only-child
CSS pseudo-class represents any element which is the only child of its parent. This is the same as :first-child:last-child
or :nth-child(1):nth-last-child(1)
, but with a lower specificity.
Browser Compatibility
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 2 | 1.5 (1.8) | 9 | 9.5 | 3.1 |
Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
Basic support | 2.1 | 1.0 (1.8) | 9 | 10.0 | 3.1 |
Specifications
Specification | Status | Comment |
---|---|---|
Selectors Level 4 The definition of ':only-child' in that specification. |
Working Draft | No change |
Selectors Level 3 The definition of ':only-child' in that specification. |
Recommendation | Initial definition |
License
© 2016 Mozilla Contributors
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-us/docs/web/css/:only-child