Search code examples
csscss-selectorspseudo-class

Why p:first-child pseudo class does not apply to p element's first-child


CSS Pseudo Class selector(first-child) for p tag applies to all p that are immediate first child to their parent why not p tag that is immediate first element of p itself.

p:first-child {
  color: blue;
}
<body>
    <p>This P is body's first Child.</p>
    <p>This is body's second child.</p>

    <div>
        <p> This P is div's first Child </p>
        <p> This is div's second child.</p>
    </div>

    <p>
        <p> This P is P's first child :: Why it does not get pseudo class</p>
        <p> This is P's second child </p>
    </p>

</body>


Solution

  • <p> tags cannot be nested in HTML. This is because they only exist to format text as.. well.. a paragraph, you can read more about it here.

    In short, any open <p> tag simply closes whatever the last <p> to be opened was, regardless of syntax.