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

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

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


当前回答

下面的代码肯定在任何地方都能正常工作。 它简单而简短。

<div class="home">
    <span>blah</span>
    <p class="blue"> first-blue  </p>
    <p class="blue"> second-blue </p>
    <p class="blue"> third-blue  </p>

    <p class="red">  first-red   </p>
    <p class="red">  second-red  </p>
    <p class="red">  third-red   </p>
    <p class="red">  fourth-red  </p>

    <p class="pink"> first-pink  </p>
    <p class="pink"> second-pink </p>

    <p class="red">  new-first-red   </p>
    <p class="red">  new-second-red  </p>
</div>

我们可以选择第一个红色:

.home .red:not(.home .red ~ .red) {
    background-color: blue;
}

如果你想选择new-first-red,你应该使用+而不是~。

其他回答

我使用下面的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>

正确答案是:

.red:first-child, :not(.red) + .red { border:5px solid red }

第一部分:如果元素是父元素的第一个,并且类为“red”,它将得到border。 第二部分:If "。红色“元素不是其父元素的第一个,而是紧跟着一个没有类的元素”。红色”,它也应该配得上说边界的荣誉。

不然就是没发生。

菲利普·多布梅尔的回答,虽然被接受,但并不正确-见附件小提琴。 BoltClock的答案可以工作,但不必要地定义和覆盖样式 (特别是一个问题,否则它将继承一个不同的边界-你不想声明other to border:none)

编辑: 如果你有“红色”后面的非红色几次,每个“第一个”红色将得到边界。为了防止这种情况,我们需要使用BoltClock的答案。看到小提琴

为了匹配选择器,元素的类名必须为红色,并且必须是其父元素的第一个子元素。

<div>
    <span class="red"></span> <!-- MATCH -->
</div>

<div>
    <span>Blah</span>
    <p class="red"></p> <!-- NO MATCH -->
</div>

<div>
    <span>Blah</span>
    <div><p class="red"></p></div> <!-- MATCH -->
</div>

试试这个解决方案:

.home p:first-of-type { 边框:5px纯红色; 宽度:100%; 显示:块; } < div class = "家" > < span >等等> < /跨度 < p class = "红色" >第一个< / p > < p class = "红色" >第二< / p > < p class = "红色" > < / p >第三 < p class = "红色" >第四< / p > < / div >

CodePen链接

下面的代码肯定在任何地方都能正常工作。 它简单而简短。

<div class="home">
    <span>blah</span>
    <p class="blue"> first-blue  </p>
    <p class="blue"> second-blue </p>
    <p class="blue"> third-blue  </p>

    <p class="red">  first-red   </p>
    <p class="red">  second-red  </p>
    <p class="red">  third-red   </p>
    <p class="red">  fourth-red  </p>

    <p class="pink"> first-pink  </p>
    <p class="pink"> second-pink </p>

    <p class="red">  new-first-red   </p>
    <p class="red">  new-second-red  </p>
</div>

我们可以选择第一个红色:

.home .red:not(.home .red ~ .red) {
    background-color: blue;
}

如果你想选择new-first-red,你应该使用+而不是~。