2014-02-20 74 views
0

我:CSS找到的第一個孩子給出錯誤的結果

<ul> 
<li id="test1">The third paragraph.</li> 
<li id="test1">The fourth paragraph.</li> 
<li id="test2">The second paragraph.</li> 
<li id="test2">The third paragraph.</li> 
<li id="test2">The fourth paragraph.</li> 
<li id="test3">The second paragraph.</li> 
<li id="test3">The third paragraph.</li> 
<li id="test4">The fourth paragraph.</li> 
<li id="test4">The fourth paragraph.</li> 
<li id="test7">The fourth paragraph.</li> 
<li id="test7">The fourth paragraph.</li> 
</ul> 

和CSS代碼:

ul > #test4:first-child 
{ 
background:#ff0000; 
} 

此代碼ul>#test1的:第一,孩子是好的,但UL>#TEST4:第一 - 小孩不工作

Demo 問題在哪裏?

回答

1

首先,元素的ID必須是唯一的,

:first-child只會匹配的第一個子元素而與用於子元素任何其他選擇,所以在你的情況下,第一#test1的將是唯一的元素匹配ul > :first-child選擇器

我不認爲有一個只有CSS的解決方案。

相反ID使用class屬性,然後使用jQuery中的:first-selector

.someclass{ 
    //some rule 
} 

然後

$('ul > .test4:first').addClass('someclass') 
+0

我第二個這個[我本來會建議這個,然後你編輯:)] – ohmusama

0

它不工作,因爲你正在尋找的<ul>元素的:first-child其中有一個名爲test4的ID。你想要的是第一個編號爲test4的元素,我認爲這對於純CSS來說是不可能的。

此外,您最好使用類而不是ID,因爲您不應該在HTML元素中重複ID。