2014-04-07 40 views
0

我遇到了一個令我困惑的場景 - :last-child的使用影響父類的應用方式。':last-child'爲什麼改變樣式的優先級?

我有一個元素列表,目標是將一些樣式應用到最後一個元素。

但是,當我使用:last-child時,樣式的優先級發生變化,其中一個父類停止工作,只有!important修復了此問題。

我做了一個簡單的演示在這裏: http://jsfiddle.net/wC2AX/1/

HTML:

<div class="hover"> 
    <div class="focus_on_last_child" style="background-color:red; width:100px; height:100px"> 
     <div class="attribution"> 

     </div> 
    </div> 
</div> 

CSS:

/*this should be applied on hover always*/ 
.hover:hover .attribution{ 
     background-color: black; /*try adding !important*/ 
     bottom: 0px; 

} 

/*basic properties*/ 
.attribution { 
    height: 60px; 
    overflow: hidden; 
    position: absolute; 
    bottom: -60px; 
    width: 100px; 
} 

/*depending on a screen size styles are changed*/ 
.focus_on_last_child:last-child .attribution { /*try removing :last:child*/ 
    background-color: pink; 
    bottom: -30px; 
} 

的例子是一個有點傻,這個想法是在懸停的風格應該被改變。但它僅在使用!important:last-child被刪除時才起作用。

感謝您的任何建議!

回答

2

這是選擇器specificity的問題。

你的第一條規則有兩個階級,一個僞類:

.hover:hover .attribution 

而且你的最後一個規則也有兩個階級,一個僞類(:last-child在於僞類):

.focus_on_last_child:last-child .attribution 

由於你的兩條規則同樣具體,所以稍後的規則優先。當您刪除:last-child僞類時,只剩下兩個類選擇器,因此該規則的特定性會降低,從而允許您的優先規則爲:hover

最簡單的解決方案是將您的:hover規則移動到:last-child規則的下方,以便規則優先,而且您不必使用!important

+0

我也注意到了。但當我讀過你已經回答的問題時...... – Arperum

+0

打我吧,我也不認爲@Anelook實際上需要最後一個子選擇器,如果html如上 – Pete

+0

我不認爲增加' :懸停在':最後一個孩子'下面是必要的。你根本不需要':最後一個孩子',請[見我的答案](http://stackoverflow.com/a/22907075/1248175) – rednaw

2

這是因爲:

.hover:hover .attribution{ 

比更具體:

.focus_on_last_child .attribution { 

但是,如果你想補充.hover它,它會更具體,將工作:

.hover .focus_on_last_child .attribution { 
相關問題