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 ごとに、3 番目に 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/

最初の の前に他の兄弟要素がある場合は、代わりdiv.postに使用する必要があります。nth-of-type

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

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

古いブラウザー (IE8 以前を含む) の場合、JavaScript が必要になります。jQuery を使用して 3 つおきの項目にクラスを追加し、そのクラスを 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

これは、jQueryfilter()と各項目のインデックスのモジュラスを使用する方法です。

インデックスは 0 ベースなので、各インデックスに 1 つ追加しています。

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

http://jsfiddle.net/XF5hS/

編集:

純粋な CSS ソリューションについては、nth childこのページのソリューションを参照してください。

それができない場合:
div を動的に生成している場合は、3 つおきの項目にクラスを追加するだけです。それらが動的でない場合でも、クラスを 3 つおきの項目にハードコードすることができます。

このようなもの:

<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 に答える
1
var i = 0;
$('.post').each(function(){
    i++;
    if(i%3==0){
        $(this).css('margin-right', '0');
    }
});
于 2013-10-09T21:05:06.180 に答える