2014-07-21 132 views
1

根據這篇文章:http://css-tricks.com/how-nth-child-works/第n個孩子選擇器應該工作不同。爲什麼css nth-child選擇器不能按預期工作?

在我的情況下,我必須使用.drag_box:nth-child(3n+2){}選擇每隔三個div,但通常應該只是.drag_box:nth-child(3n){}。怎麼來的?這裏是小提琴:

http://jsfiddle.net/6bRY7/2/

這裏的代碼:

HTML:

<div id="content_box_search"> 
    <label> 
     <input type="text" class="search" name="word"/> 
     <span class="search-icon"></span>      
    </label> 
</div> 
<div id="search_go">Go</div> 
<div id="content_box_upload"> upload </div> 
<div style="clear: both; height: 20px;"></div> 



<div class="drag_box"></div> 
<div class="drag_box"></div> 
<div class="drag_box"></div> 
<div class="drag_box"></div> 
<div class="drag_box"></div> 
<div class="drag_box"></div> 
<div class="drag_box"></div> 
<div class="drag_box"></div> 
<div class="drag_box"></div> 
<div class="drag_box"></div> 
<div class="drag_box"></div> 

的Javascript:

$(document).ready(function() { 
    $('#search_go').hide(); 
    $('.search').bind('input', function() { 
     if ($(this).val()) { 
      $('#search_go').fadeIn(1000); 
     } 
     else { 
      $('#search_go').fadeOut(1000); 
     } 
    }); 
}); 

CSS:

.drag_box{ 
    position: relative; 
    float: left; 
    width:30%; 
    height: 30px; 
    background-color:#ccc; 
    margin-right:5%; 
    margin-bottom:10px; 
} 

/* .drag_box:nth-child(3n+1){ */ 

.drag_box:nth-child(3n+2){ 
    margin-right: 0; } 

#content_box_search{ 
    float: left; } 

#search_go{ 
    float: left; 
    font-size: 12px; 
    margin-left: 10px; 
    background-color: #dedede; 
    color: #646464; 
    cursor: pointer; 
    height: 25px; 
    line-height: 25px; 
    text-align: center; 
    width: 50px;  } 

#content_box_upload{ 
    float: right; 
    width: 200px; 
    height: 25px; 
    line-height: 25px; 
    text-align: center; 
    background-color: #dedede; 
    color: #646464; 
    cursor: pointer; 
    } 
+5

'n-child'在元素上工作,而不是元素類。 – j08691

+0

啊,很高興知道!謝謝! – user2718671

回答

2

因爲所有父元素的子元素算作兒童(然後將其算作n S),而不僅僅是與匹配的類名的人。

相關問題