2013-08-07 44 views
2

選擇第一個孩子,我想知道如何在實際範圍選擇第一個孩子,讓我給你的例子,所以你能正確地理解我的問題:CSS:在實際範圍

HTML:

首先來到我的腦海影響commentCompany類中,但只有在直接範圍類commentTop,commentMiddle,commentBottom
<div class="comment commentCompany"> 
    <div class="commentTop"></div> 
    <div class="commentMiddle"> 
    Text of comment level two comment. 
    <div class="comment"> 
     <div class="commentTop"></div> 
     <div class="commentMiddle"> 
     Text of comment level three. 
     </div> 
     <div class="commentBottom"></div> 
    </div> 
    </div> 
    <div class="commentBottom"></div> 
</div> 

CSS是這樣的:

.commentCompany .commentTop:first-child{/*affect company's .commentTop*/} 
.commentCompany .commentMiddle:first-child{/*affect company's .commentMiddle*/} 
.commentCompany .commentBottom:first-child{/*affect company's .commentBottom*/} 

但是這裏有兩個問題:第一個孩子更像第一類元素的類型(不是真正的第一個孩子的類)(將不得不使用第n個孩子),而且它也影響嵌套註釋 - 這不是公司的評論 - 那麼如何才能獲得直接的評論範圍公司?

我想知道CSS2 & & CSS3的解決方案,如果有任何區別。謝謝! :)

回答

5

你希望孩子組合子>而不是:first-child:nth-child()僞類:

.commentCompany > .commentTop 
.commentCompany > .commentMiddle 
.commentCompany > .commentBottom 

此只選擇.commentTop.commentMiddle.commentBottom是直接嵌套在.commentCompany(你所謂的內稱爲「實際範圍」)。有關說明,請參閱this answer

使用空間,後代組合子,意味着你正在試圖獲取嵌套在.commentCompany中的父代的每個第一個孩子。將它與你的類選擇器相結合,你會得到各種意想不到的結果。

子組合器是CSS2的一部分;沒有CSS3的解決方案。

+0

更不用說:第一個孩子和第n個孩子()在CSS2和CSS3之間的行爲非常不同 – Charles380

+1

@ Charles380:':first-child'與':nth-​​child(1)'完全相同。 – BoltClock

+0

@BoltClock抱歉與CSS2沒有:nth-​​child()這就是我得到的 – Charles380