为什么css nth-child选择器不能按预期工作?

时间:2014-07-21 13:34:36

标签: html css css-selectors

根据这篇文章:http://css-tricks.com/how-nth-child-works/ 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;
     }

1 个答案:

答案 0 :(得分:2)

因为所有,父元素的子元素计为子元素(然后计为n s),而不仅仅是具有匹配类名的子元素。