2012-11-17 94 views
0

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

謝謝!

回答

2

p:last-child選擇p是其父項的最後一個子項的元素,因此它之後沒有任何同級元素。 <p> I expect that this will have a pink background but it won't :(Why? </p>後面跟着一個div這是最後一個孩子,而不是它以前的兄弟p

我想你想要的是:last-of-type僞類。 p:last-of-type {background: pink;}將選擇你想要的元素。

4

當我使用:last-child選擇,它只能選擇文檔的最後孩子,而:first-child選擇器選擇所有文檔的第一個孩子。

這是不正確的。他們都分別選擇全部父母的最後和第一個孩子。你或者誤解了「最後一個孩子」和「第一個孩子」的含義,或者誤解了你的頁面結構。

p:first-child這裏兩個元素相匹配,因爲divbody第一個孩子的第一個孩子都是p元素。

p:last-child只匹配一個元素,因爲你div的最後一個孩子是p,但body最後一個孩子是div,不是p

縮進你的HTML一點會說明清楚:

<body> 
    <p></p> <!-- First child of body is p --> 
    <p></p> 
    <p></p> 
    <div>  <!-- Last child of body is div --> 
    <p></p> <!-- First child of div is p --> 
    <p></p> 
    <p></p> <!-- Last child of div is p --> 
    </div> 
</body> 

如前所述,您很可能希望選擇第一個和最後p元素,在這種情況下,你應該使用p:first-of-typep:last-of-type代替。