CSSS: Pseudo-class selector not working as expected

Hello,

Good Day,

In CSS, When I use Pseudo-Class selector: first-child, it is not styling the immediate first element instead it applies the style to all the elements declared in the article HTML page.

Please find my sample code below:
HTML

Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet.

CSS:
article:first-child{
color:blue;
}

I want to apply style only for the first child element declared in the article part.

It’d be more helpful if you could assist with this as I need to know the reason for this error.

Thanks,
Raj

Your CSS rule is saying “find all article elements that are a first child, and set their color property to blue”. Well, your article element is a first child, so its color property, and all of the elements within it, are set to blue. So you just need a slight adjustment to your CSS in order to select the right type of element.

<html>
  <head>
    <style>
      p:first-child {
        color: blue;
      }
    </style>
  </head>
  <body>
    <article>
      <p>Lorem ipsum dolor sit amet.</p>
      <p>Lorem ipsum dolor sit amet.</p>
    </article>
  </body>
</html>

Change the selector to article :first-child (space between article and :first-child) to select the first child of any article instead of any article that is the first child of its parent.

1 Like