【问题标题】:How do i style two same class divs differently?我如何以不同的方式设计两个相同的类 div?
【发布时间】:2017-09-02 23:03:18
【问题描述】:

所以基本上我有一个设置,以以下方式吐出代码..

<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 个孩子,但无法达到我想要的结果。无法向现有的“TARGETCLASS”类添加额外的类或 ID。否则我不会发布这个问题:)

另外,“子父”类也是一样的。对于两个目标类类。这就是问题 提前感谢您抽出宝贵时间为我回答这个问题。

干杯!

【问题讨论】:

标签: css css-selectors


【解决方案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/

【讨论】:

    【解决方案2】:

    我会像这样使用第 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
    

    nth-of-type() 选择器使您可以在系列中设置特定元素的样式,在这种情况下,我们定位第二个 .subparent 然后指定我们需要的子元素。 我希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      看来,它正在由第 n 个孩子工作。 这是关于如何称呼儿童的。不像“让父母找到第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> 

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-08-09
        • 1970-01-01
        • 2023-02-07
        • 1970-01-01
        • 2017-06-23
        • 2023-03-29
        • 2011-05-12
        相关资源
        最近更新 更多