CSS :only-child

The CSS :only-child pseudo-class is used when we need to select element that is the only child of its parent element. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      p:only-child {background-color: #ccc; padding: 10px;}
      li:only-child {background-color: #ccc; padding: 10px;}
   </style>
</head>
<body>

   <p>This is para one.</p>
   <div>
      <p>This is para one, inside DIV one (the only para inside this DIV).</p>
   </div>
   <p>This is para two.</p>
   <div>
      <p>This is para one, inside DIV two.</p>
      <p>This is para two, inside DIV two.</p>
   </div>
   <ul>
      <li>one (the only list item inside this unorganized list)</li>
   </ul>
   <p>This is para three.</p>
   <ul>
      <li>first</li>
      <li>second</li>
   </ul>
   
</body>
</html>
Output

This is para one.

This is para one, inside DIV one (the only para inside this DIV).

This is para two.

This is para one, inside DIV two.

This is para two, inside DIV two.

  • one (the only list item inside this unorganized list)

This is para three.

  • first
  • second

CSS Online Test


« Previous Tutorial Next Tutorial »

Follow/Like Us on Facebook




Subscribe Us on YouTube