[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
style.css
/* Style a p element if it is the only child of a div */
div p:only-child { color: red;}
/* Style the sole child of .hoge */
div.hoge :only-child { color: blue;}
/* Make a single image fill the card */
.card img:only-child { width: 100%;}
/* Hide list markers when there is only one item */
li:only-child { list-style: none;}
/* Center-align when there is only one child */
.wrapper :only-child { margin: 0 auto;}
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
1 and earlier ×
2 and earlier ×
8 ×
7 ×
6 ×
8 and earlier ×
1 and earlier ×
Android Browser
4.4+ ○
3 and earlier ×※ Version data is based on MDN.
If you find any errors or copyright issues, please contact us.