2014-09-13 144 views
2

使用CSS:我如何定位第一類「方法」,第二類和第三類。所有人都是因爲他們需要不同的風格我無法添加額外的課程以避免響應性迷失方向。CSS選擇:nth-​​of-class()替代方案

HTML代碼:

<div class="approaches"> 
    <div class="col-md-4"> 
     <a href="#" class="approach">content here...</a> 
    </div> 
    <div class="col-md-4"> 
     <a href="#" class="approach">content here...</a> 
    </div> 
    <div class="col-md-4"> 
     <a href="#" class="approach">content here...</a> 
    </div> 
</div> 

CSS代碼(不目前工作):

.approaches .approach:nth-of-type(1){ 
    color: red; 
} 
.approaches .approach:nth-of-type(2){ 
    color: green; 
} 
.approaches .approach:nth-of-type(3){ 
    color: blue; 
} 
+0

你能把class =「approach」提升到div的水平嗎? – kornieff 2014-09-13 08:22:27

回答

2

還有的.approaches.approach元素之間的<div>防止您的:nth選擇從工作正常。選擇器在自己的嵌套級別中查找元素,並且由於.approach元素被包裝在<div>中,因此它們具有單獨的嵌套級別。在<div>■使用選擇器來代替:

.approaches div:nth-of-type(1) .approach { 
    color: red; 
} 
.approaches div:nth-of-type(2) .approach { 
    color: green; 
} 
.approaches div:nth-of-type(3) .approach { 
    color: blue; 
} 
+0

感謝您的明確答案。之前從未使用過這種類型的選擇器,也不知道嵌套問題。 – user2381011 2014-09-13 08:20:15

1

你可以使用.approaches div:nth-of-type(1) .approach { },正如其他人的建議,但是這是假定每個DIV中.approaches已與該.approach類的a,所以它不能真正被認爲是實現相當於不存在的nth-of-class的一般方法,如果這是你想要的。

要做到這一點,你可以使用一點的JS:

[].forEach.call(document.getElementsByClassName('approach'), function(elt, i) { 
    elt.classList.add('approach-' + i); 
}); 

.approach-1 { color: red; } 

歸納這對於所有等級:

function add_nth_of_class(cls) { 
    [].forEach.call(document.getElementsByClassName(cls), function(elt, i) { 
     elt.classList.add(cls + '-' + i); 
}); 

add_nth_of_class('approach'); 

然而,這個人數將達到類依次整個文檔。要獲得真正的nth-of-class,基於父元素中的位置,我們需要做的類似於以下,使用鮮爲人知的TreeWalker API:

function add_nth_of_class(cls) { 
    var walker = document.createTreeWalker(document, NodeFlter.SHOW_ELEMENT), n; 

    while (n = walker.nextNode()) {     //for each node in turn, 
     [].filter.call(n.childNodes, function(elt) { //find the children which 
      return elt.classList.contains(cls);  //contain the class we want 
     }).forEach(function(elt, i) {     //and for each of those 
      elt.classList.add(cls + '-' + (i+1));  //add a numbered class 
     }); 
    } 
} 

CSS:

.approach-1 { // targets all elements with class .approach first within their parent 
-1
.approaches > div:nth-child(1) .approach { 

} 

.approaches > div:nth-child(2) .approach { 

} 

.approaches > div:nth-child(3) .approach { 

}