0

我有这个代码:

<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>

和CSS:

.post {position:relative;float:left;margin-right:10px;}

我需要每个 3 div.post,第三个有 margin-right:0px;

4

5 回答 5

6
.post:nth-child(4n)
{
    margin-right:0px;
} 
于 2013-10-09T21:03:30.957 回答
2

对于现代浏览器,纯 CSSnth-child选择器就足够了:

.post:nth-child(3n) { /* not zero-based */
    margin-right: 0px;
} 

http://jsfiddle.net/mblase75/EQacc/

如果在 first 之前还有其他兄弟元素div.post,您将需要使用nth-of-type

.post:nth-of-type(3n) {
    margin-right:0px;
}

http://jsfiddle.net/mblase75/4vnjt/

对于较旧的浏览器(包括 IE8 和更早版本),需要一些 JavaScript。我会使用 jQuery 为每第三个项目添加一个类,并将该类添加到我的 CSS 中:

.post.thirdchild, .post:nth-child(3n) {
    margin-right: 0px;
} 

jQuery:

$('.post:nth-of-type(3n)').addClass('thirdchild');

http://jsfiddle.net/mblase75/Tf9ky/

为什么包括两者?好吧,有些用户可能关闭了 JavaScript。


事实上,如果您担心 IE<8,理想的解决方案可能是将 0px 作为默认边距,这样帖子就不会溢出其容器:

.post {
    position: relative;
    float: left;
    margin-right: 0px;
}
.post.notthirdchild,
.post:nth-child(3n+1), 
.post:nth-child(3n+2) {
    margin-right: 10px;
} 

JS:

$('.post:nth-child(3n+1),.post:nth-child(3n+2').addClass('notthirdchild');

http://jsfiddle.net/mblase75/nBLxc/

于 2013-10-09T21:23:43.190 回答
1
var i = 0;
$('.post').each(function(){
    i++;
    if(i%3==0){
        $(this).css('margin-right', '0');
    }
});
于 2013-10-09T21:05:06.180 回答
1
$(".post:nth-of-type(3n)").css("margin-right", "0");

http://jsfiddle.net/fabricis/7GUwQ/

于 2013-10-09T21:17:06.923 回答
1

这是一个使用 jQueryfilter()和每个项目索引的模数的方法。

索引是从 0 开始的,所以我要为每个索引添加一个。

$('.post').filter(function (index) {
    return ((index + 1) % 3 == 0 ? 1 : 0)
}).css('margin-right', '0px');

http://jsfiddle.net/XF5hS/

编辑:

对于纯 CSS 解决方案,请参阅nth child此页面上的解决方案。

失败:
如果你动态生成你的 div,你可以每三个项目添加一个类。如果它们不是动态的,您仍然可以将一个类硬编码到每三个项目。

像这样的东西:

<div class="post"></div>
<div class="post"></div>
<div class="post no-margin"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post no-margin"></div>
div.post.no-margin {
  margin-right:0px;
}
于 2013-10-09T21:17:09.803 回答