我已经尝试了几次,每次都会发生以下情况:当我使用:last-child
选择器时,它只选择文档的最后一个孩子,而:first-child
选择器选择文档的所有第一个孩子。有人可以解释我为什么吗?
例子:
:第一个孩子
<style>
p:first-child {background: pink;}
</style>
<body>
<p> This is the first child of the body so the background color is pink </p>
<p> This is some text in a paragraph </p>
<p> This is some text in a paragraph </p>
<div>
<p> This is the first child of the div so the background color is also pink </p>
<p> This is some text in a paragraph </p>
<p> This is some text in a paragraph </p>
</div>
</body>
:最后一个孩子
<style>
p:last-child {background: pink;}
</style>
<body>
<p> This is some text in a paragraph </p>
<p> This is some text in a paragraph </p>
<p> I expect that this will have a pink background but it won't :( Why? </p>
<div>
<p> This is some text in a paragraph </p>
<p> This is some text in a paragraph </p>
<p> This is the last child of div and only this paragraph has a pink background </p>
</div>
</body>
谢谢!