The :only-child selector matches every element that is the only child of its parent. In this example, the selector specifies a background color for every <p> element that is the only child of its parent:
HTML file: | Displayed by browser: |
---|---|
<style>
p:only-child { background: #ff0000; } </style> <body> <div><p>This is a paragraph.</p></div> <div><span>This is a span.</span> <p>This is a paragraph.</p></div> </body> |
This is a paragraph. This is a span.
This is a paragraph. |
The first paragraph is an only child of the first div element. The span and the last paragraph are both children of the second div element. Note: Internet Explorer 8 and earlier versions do not support the :only-child selector