CSS :first-child - Style First Child Element

The CSS :first-child pseudo-class selects the first child element of its parent. For example, the following CSS code applies style to all P, that are of course the first child of their parent element:

p:first-child {background-color: #ccc; padding: 10px;}

CSS :first-child Example

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      p:first-child {background-color: turquoise; padding:10px; text-align: center;}
      li:first-child {color: red;}
   </style>
</head>
<body>

   <p>This is para one.</p>
   <p>This is para two.</p>
   <div>
      <p>This is para one, inside DIV.</p>
   </div>
   <ul>
      <li>one</li>
      <li>two</li>
      <li>three</li>
   </ul>
   
</body>
</html>
Output

This is para one.

This is para two.

This is para one, inside DIV.

  • one
  • two
  • three

CSS Online Test


« Previous Tutorial Next Tutorial »

Follow/Like Us on Facebook




Subscribe Us on YouTube