2016-08-12 13 views
2

上記の子の直接の親ではないセレクタの疑似クラスnth-childをどのように使用しますか?ハイレベルセレクタのn番目の子を選択してください

HTML

<div id="main"> 
</div> 

CSS

.test { 
    width: 100px; 
    height: 100px; 
    background: red; 
} 

#main .test:nth-child(even) { 
    background: green; 
} 

JS

// doesnt work 
for (var i = 0; i < 3; i++) { 
    $('#main').append('<div><div class="test"></div></div>') 
} 
// works 
for (var i = 0; i < 3; i++) { 
    $('#main').append('<div class="test"></div>') 
} 

JSFiddle

+0

偶数または奇数が必要な場合はnth-of-typeを使用するはずですが、なぜ動作していないのかはわかりません。なぜ、親のdivを背景と一緒にするのはなぜですか? – Omeed

+0

:nth-​​child(n)セレクタは、**親**のn番目の子であるすべての要素に一致します。 – Steve

答えて

3

あなたが.testのdivを選択したい場合は、内.testを選択し、#mainの全ての偶数子を選択する必要があります。

CSS

#main div:nth-child(even) .test { 
    background: green; 
} 

JSFiddle

+0

私は '#main .test {padding-right:100px; } ''#main'内の '.test'をすべて選択しますが、このクラスを使って同様のロジックを適用することはできません。 – BarryBones41

+1

残念なことに、 "nth-of-class"のようなものはありません.nth-child型またはnth-of-typeを扱い、親子構造体を保持する必要があります。回避策はjqueryだけです。ベストアイデア – Honza

1

あなたのhtml内の構造の二つの異なる種類を持っているとして、

#main .test:nth-child(even) , 
#main div:nth-child(even) > .test{ 
    background: green; 
} 

https://jsfiddle.net/9yq0bhjk/4/

をスタイリングのための別のセレクタを使用
関連する問題