only-child property

Image Tutorials

Definition and Usage

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.


Syntax

parent child:only-child {
  property: value;
}

Examples

Basic example

1 span:only-child {
2   colorred;
3 }
1 <div>
2     <span>This span is the only child of its father</span>
3 </div>
4 <div>
5     <span>This span is one of the two children of its father</span>
6     <span>This span is one of the two children of its father</span>
7 </div>

Reference result

This span is the only child of its father
This span is one of the two children of its father
This span is one of the two children of its father

A list example

1 li li {
2   list-style-typedisc;
3 }
4 li:only-child {
5   color#6699ff;
6   font-styleitalic;
7   list-style-typesquare;
8 }
01 <ol>
02     <li>First
03         <ul>
04             <li>This is only child element
05         </ul>
06     </li>
07     <li>Second
08         <ul>
09             <li>This list has two elements
10             <li>This list has two elements
11         </ul>
12     </li>
13     <li>Third
14         <ul>
15             <li>This list has three elements
16             <li>This list has three elements
17             <li>This list has three elements
18         </ul>
19     </li>
20 <ol>
  1. First
    • This list has only one element
  2. Second
    • This list has two elements
    • This list has two elements
  3. Third
    • This list has three elements
    • This list has three elements
    • This list has three elements

Another example

1 p:only-child {
2     background#6699ff;
3     width350px;
4 }
1 <div>
2     <p>This is a paragraph with :only-child</p>
3 </div>

This is a paragraph with :only-child


Compatibility

Desktop browsers

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 2 1.5 (1.8) 9 9.5 3.1

Mobile browsers

Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 2.1 1.0 (1.8) 9 10.0 3.1
Rate article