CSS :first-child property


The :first-child pseudo-class in CSS targets the first child element of a specified parent element. It allows you to apply styles specifically to the first child, regardless of its type. This is useful for styling elements differently based on their position within a container.

Syntax

parent-selector:first-child { /* styles */ }
  • parent-selector: The selector targets the parent element.
  • :first-child: The pseudo-class applies styles to the first child of the parent element.

How It Works

  1. Basic Usage:

    • You use :first-child to apply styles to the first child element of a parent container.
    ul li:first-child { font-weight: bold; }
    • In this example, the first <li> element within each <ul> will be styled with bold text.
  2. Compatibility:

    • The :first-child pseudo-class works with any type of element. It’s not limited to specific tags, and it applies based on the element's position as the first child of its parent.

Example

HTML

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>First Child Example</title> <style> ul li:first-child { color: green; font-weight: bold; } ol li:first-child { color: red; font-style: italic; } </style> </head> <body> <ul> <li>First item (ul)</li> <li>Second item (ul)</li> <li>Third item (ul)</li> </ul> <ol> <li>First item (ol)</li> <li>Second item (ol)</li> <li>Third item (ol)</li> </ol> </body> </html>

Explanation:

  • ul li:first-child:

    • Targets the first <li> element within each <ul>. This first list item is styled with green text and bold font weight.
  • ol li:first-child:

    • Targets the first <li> element within each <ol>. This first list item is styled with red text and italic font style.

Important Points

  1. Type of First Child:

    • :first-child applies only if the element is the very first child of its parent. If the parent has other non-element nodes (like text nodes or comments) before the target element, :first-child will not apply.
    <div> <!-- A comment --> <p>This paragraph is the first child.</p> </div>
    div p:first-child { color: blue; }
    • In this case, the :first-child pseudo-class will not apply to <p> because it is preceded by a comment node.
  2. Combination with Other Selectors:

    • :first-child can be combined with other pseudo-classes and selectors for more specific styling.
    ul > li:first-child { color: green; }
    • This example targets only <li> elements that are the direct children of a <ul> and are the first child.
  3. Use in Nested Structures:

    • In nested structures, :first-child will only apply to the very first child of each parent element.
    div > p:first-child { color: red; }
    • This targets <p> elements that are the first child of their parent <div>, but not <p> elements that might be deeper in the structure.