我有一堆元素的类名红色,但我似乎不能选择class="red"使用以下CSS规则的第一个元素:

.home .red:第一个孩子{ 边框:1px纯红色; } < div class = "家" > < span >等等> < /跨度 < p class = "红色" >第一个< / p > < p class = "红色" >第二< / p > < p class = "红色" > < / p >第三 < p class = "红色" >第四< / p > < / div >

这个选择器出了什么问题,我如何纠正它,以类红色为目标的第一个孩子?


当前回答

我想很多人已经解释过了。您的代码只选择了第一个实例的第一个子对象。如果你想选择红色类的所有第一个子类,你需要使用

.home > .red:first-child {
    /* put your styling here */
}

其他回答

只使用

.home > .red ~ .red{
 border: 1px solid red;
}

它会起作用的。

出于某种原因,上述答案似乎都没有解决父母真正的第一个和唯一的第一个孩子的情况。

#element_id > .class_name:first-child

如果您只想将样式应用于此代码中的第一个子类,那么以上所有答案都将失败。

<aside id="element_id">
  Content
  <div class="class_name">First content that need to be styled</div>
  <div class="class_name">
    Second content that don't need to be styled
    <div>
      <div>
        <div class="class_name">deep content - no style</div>
        <div class="class_name">deep content - no style</div>
        <div>
          <div class="class_name">deep content - no style</div>
        </div>
      </div>
    </div>
  </div>
</aside>

我想很多人已经解释过了。您的代码只选择了第一个实例的第一个子对象。如果你想选择红色类的所有第一个子类,你需要使用

.home > .red:first-child {
    /* put your styling here */
}

我使用下面的CSS有一个背景图像列表ul li

#footer .module:nth-of-type(1)>.menu>li:nth-of-type(1){ background-position: center; background-image: url(http://monagentvoyagessuperprix.j3.voyagesendirect.com/images/stories/images_monagentvoyagessuperprix/layout/icon-home.png); background-repeat: no-repeat; } <footer id="footer"> <div class="module"> <ul class="menu "> <li class="level1 item308 active current"></li> <li> </li> </ul> </div> <div class="module"> <ul class="menu "><li></li> <li></li> </ul> </div> <div class="module"> <ul class="menu "> <li></li> <li></li> </ul> </div> </footer>

由于其他答案涵盖了它的问题,我将尝试另一半,如何解决它。不幸的是,我不知道你有一个CSS唯一的解决方案,至少不是我能想到的。还有一些其他的选择....

在生成元素时给元素赋一个first类,如下所示: <p class="red first"></p> . < div class = "红色" > < / div > CSS: 当代。红色{ 边框:5px纯红色; } 这个CSS只匹配第一个类和红色类的元素。 或者,在JavaScript中做同样的事情,例如这里是你会使用jQuery来做这件事,使用与上面相同的CSS: $ (r:首先).addClass(“第一”);