2017-09-02 27 views
0

所以基本上我已经得到了吐出来以下列方式将代码安装..我如何对两个相同的类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“以另一种方式排在第二位。我试过第n个孩子,但无法达到我期待的结果。没有办法将其他类或ID添加到现有的“TARGETCLASS”类中。否则,我不会发布这个问题:)

此外,“subparent”类也是相同的。对于这两个目标类的类。这是问题 在此先感谢您花时间为我回答这个问题。

干杯!

+0

[n个子selctor CSS(可能的重复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级的类型()选择使您能够风格在这个例子中,我们针对第二个.subparent然后指定了我们需要的孩子。 我希望这有助于!

+1

完美。这笔交易已经完成。谢啦! – Ashtheslayer

1

看起来你在你的html中有一些不正常的标签。 nth-child应该可以正常工作。此外,请确保将nth-child选择器放置在subparent类上,而不是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来定位第一个,第二个可以使用.parent .subparent:nth-of-type(2)

(您可以用同样的方式使用first-childnth-child只有所有parent孩子有类subparent

观看演示如下:

.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个工作ILD。 这是关于如何称为儿童。不喜欢“问父母找n个子,不过问孩子,是他如何远离父母”

.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>

相关问题