我試了幾次,每次發生下一件事: 當我使用: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>
謝謝!