2017-09-02 6 views
0

だから、基本的に、私は次の方法でコードを吐き出すセットアップを持っている...2つの同じクラスのdivのスタイルを変更するにはどうすればよいですか?

<div class="parent"> 
    <div class="subparent"> 
     <div class="TARGETCLASS"></div> 
    </div> 
    <div class="subparent"> 
     <div class="TARGETCLASS"></div> 
    </div> 
</div> //close for the parent class 

今、私は何をしようとしているが、一方向の上に来るスタイル「TARGETCLASS」にあり、「 「TARGETCLASS」は別の方法で2番目に来ます。私はn番目の子供を試しましたが、私が探している結果を達成することができませんでした。既存の "TARGETCLASS"クラスにクラスやIDを追加する方法はありません。そうでなければ、私はこの質問を投稿していないでしょう:)

また、 "サブ親"クラスも同じです。両方のターゲットクラスクラスに対してそれは問題です 私のためにこの質問に答える時間を取ってくれて前もってありがとう。

乾杯!

+0

[n番目の子selctorのCSS]の可能性の重複を「彼は親からどれだけ離れているかを、n番目の子を見つけるために親を掲載しますが、子供を頼む」https://stackoverflow.com/questions/40400955/nth-child-selctor-css) – Hobo

答えて

0

私はそうのように、n番目-のタイプセレクタを使用します。

.parent{} 
.parent > .subparent {} //targets both subparents 
.parent > .subparent:nth-of-type(2) {} //targets the second subparent 
.parent > .subparent:nth-of-type(2) > .TARGETCLASS{} //targets the child of the second subparent 

n番目-の型()セレクタは、スタイルを可能にしますこの場合、2番目の.subparentを指定し、必要な子を指定しました。 私はこれが助けてくれることを願っています!

+1

が完璧です。それが取引を封鎖した。ありがとう! – Ashtheslayer

1

あなたのhtmlに不正な形式のタグがあるようです。 nth-childはうまくいくはずです。また、nth-childセレクタをクラスに配置し、TARGETCLASSではなく配置してください。子セレクタを間違って配置するのは一般的です。これを試してみてください:

<div class="parent"> 
    <div class="subparent"> 
    <div class="TARGETCLASS"> 
     first-child 
    </div> 
    </div> 
    <div class="subparent"> 
    <div class="TARGETCLASS"> 
     second-child 
    </div> 
    </div> 
</div> 

<style> 
.parent .subparent .TARGETCLASS { 
    background-color:#f00; 
} 
.parent .subparent:nth-child(1) .TARGETCLASS { 
    background-color:#0f0; 
} 
</style> 

フィドル:https://jsfiddle.net/8ejxokuj/

0

.parent .subparent:first-of-typeを使用して最初のものをターゲティングし、2番目のものを.parent .subparent:nth-of-type(2)とすることができます。

(あなたがparentのみすべてかの子供たちがクラスsubparentを持っているのと同じ方法でfirst-childnth-childを使用することができます)

デモは、以下を参照してください:

.parent .subparent:first-of-type .TARGETCLASS { 
 
    color: red; 
 
} 
 

 
.parent .subparent:nth-of-type(2) .TARGETCLASS { 
 
    color: green; 
 
}
<div class="parent"> 
 
    <div class="subparent"> 
 
    <div class="TARGETCLASS">one 
 
    </div> 
 
    </div> 
 
    <div class="subparent"> 
 
    <div class="TARGETCLASS">two 
 
    </div> 
 
    </div> 
 
</div>

+0

@Ashtheslayer upvoteこの回答がお役に立てれば、ありがとう! – kukkuz

0

これは、n番目のchで動作しているようですild。 子どもがどのように呼び出されるかについてです。好きではない(

.parent .subparent:nth-child(1) {background: #FEE; color:RED;} 
 
.parent .subparent:nth-child(2) {background: #EEF; color:blue;}
<div class="parent"> 
 
<div class="subparent"> 
 
<div class="TARGETCLASS">aaa</div> 
 
</div> 
 
<div class="subparent"> 
 
<div class="TARGETCLASS">bbb</div> 
 
</div> 
 
//close for the parent class 
 
</div>

関連する問題