我有一堆元素的类名红色,但我似乎不能选择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,你应该使用+而不是~。

其他回答

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

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

你可以试试这样做吗:

.red:first-of-type {
    border: 5px solid red;
}

你也可以在最后一个元素上使用this(如果你需要的话):

.red:last-of-type {
    border: 5px solid red;
}

试试这个简单有效的方法

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

你可以使用first-of-type或n -of-type(1)

r { 颜色:绿色; } /* .red:n -of-type(1) */ r: first-of-type { 颜色:红色; } < 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,你应该使用+而不是~。