Why is first-Child selecting the <p> element?

Asked

Viewed 36 times

0

<!doctype html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        :first-child {
            border: 1px solid red;
        }
    </style>
</head>
<body>
    <p>Este é um parágrafo.</p>
    <p>Este é um parágrafo.</p>
    <p>Este é um parágrafo.</p>
</body>
</html>

In the example above the first-child is selecting and applying an edge to the element <body> and in the element <p> because this is happening wasn’t just for the element body receive the border since it is the first child element of the document?

Note: in the stackoverflow does not work has to be in a separate document.

1 answer

1


You will need to identify to which element first-Child will be applied. In this case, as you did not specify, he applied to the body.

Try the following code:

p:first-child {
        border: 1px solid red;
    }

In this case, the border shall be applied to its first paragraph.


If you want your edge to be applied to the body, try using

body{
  border: 1px solid red;
}
  • But because it occurs from first-child apply edge to element <body> and <p>?

  • 2

    @joãobatista I just tested here, and in reality what happens to your code is that because there is no specified tag, it will apply to all first children. https://developer.mozilla.org/en-US/docs/Web/CSS/:first-Child

  • True! That’s right, thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.