html - 为什么 css nth-child 选择器没有按预期工作?

标签 html css css-selectors

<分区>

根据这篇文章:http://css-tricks.com/how-nth-child-works/第 n 个子选择器的工作方式应该有所不同。

在我的例子中,我必须使用 .drag_box:nth-child(3n+2){} 来选择每三个 div,但通常它应该只是 .drag_box:nth-child (3n){}。怎么会?这是 fiddle :

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;
     }

最佳答案

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

关于html - 为什么 css nth-child 选择器没有按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24866428/

相关文章:

javascript - 如何使用 Angular 在页面加载时设置事件状态

html - 为什么类型为 ="submit"的输入框比给定的高度要矮?

css - 分组 CSS 选择器 &::selection

vb.net - 从列表中进行选择的最佳方法 - 这两个列表框是不是有点过时了?

jquery - HTML5 视频 : Recognize a new source

html - 将段落内的文本 "figure x"设为粗体

php - PHP 分页期间查询丢失重要信息

html - 有没有办法从打印中只隐藏父元素?

css - Odoo:如何编辑发票/报价布局 CSS

html - CSS sibling ,首先