2015-05-06 64 views
0

我想從我的CSS選擇器中選擇了嵌套李如何選擇第一個兄弟姐妹的第一個孩子?

Demo

li:first-child { 
 
    background-color: rgb(236, 236, 236); 
 
    list-style-type: none; 
 
    margin-bottom: 3px; 
 
    padding: 8px; 
 
}
<ul> 
 
    <li>to be selected</li> 
 
    <li></li> 
 
    <li> 
 
     <ul> 
 
      <li>not to be selected</li> 
 
      <li></li> 
 
      <li></li> 
 
     </ul> 
 
    </li> 
 
     
 
</ul>

回答

5

無論第一ul的父母被使用,然後>(這意味着即時兒童,瞭解更多here)。像這樣。

body > ul > li:first-child { 
 
    background-color: rgb(236, 236, 236); 
 
    list-style-type: none; 
 
    margin-bottom: 3px; 
 
    padding: 8px; 
 
}
<ul> 
 
    <li>to be selected</li> 
 
    <li></li> 
 
    <li> 
 
     <ul> 
 
      <li>not to be selected</li> 
 
      <li></li> 
 
      <li></li> 
 
     </ul> 
 
    </li> 
 
</ul>

+1

你打我給它 – Akshay

+0

這可能是一個明顯的問題,但爲什麼'體> ul> li:第一個孩子的工作,但是'ul> li:第一個孩子'不是? 'body'看起來像是一個冗餘選擇器,除非它只需要jsfiddle env – atmd

+0

@atmd它意味着直接的孩子。 – Ruddy

1

您可以設置的樣式,然後復原。

li:first-child { 
    background-color: rgb(236, 236, 236); 
    list-style-type: none; 
    margin-bottom: 3px; 
    padding: 8px; 
} 

li li:first-child { 
    background-color: inherit; 
    list-style-type: inherit; 
    margin-bottom: inherit; 
    padding: inherit; 
} 

小提琴; https://jsfiddle.net/wLspzcho/

+0

我記得IE6我們必須這樣做,因爲後面會介紹[子組合器](http://www.w3.org/TR/css3-selectors/#child-combinators)。 – skobaljic

1

我不知道這是你想要什麼,但試試這個

.first > li:first-child { 
 
    background-color: rgb(236, 236, 236); 
 
    list-style-type: none; 
 
    margin-bottom: 3px; 
 
    padding: 8px; 
 
}
<ul class="first"> 
 
    <li>to be selected</li> 
 
    <li></li> 
 
    <li> 
 
     <ul> 
 
      <li>not to be selected</li> 
 
      <li></li> 
 
      <li></li> 
 
     </ul> 
 
    </li> 
 
     
 
</ul>

相關問題