CSS第一个孩子或最后一个孩子是否与班级合作?

Jis*_*V S 4 html css

也许这个问题很荒谬,但我想知道这个事实.我有一个li带有两个类的元素(见下文),但它没有像我预期的那样工作.有人知道原因吗?

.red:first-child {
    color:#F00;
}
.blue:first-child {
    color:#00F; /* not working */
}
.red:last-child {
    color:#F00; /* not working */
}
.blue:last-child {
    color:#00F; 
}
Run Code Online (Sandbox Code Playgroud)
<ul>
    <li class="red">one</li> <!-- This is the first child of red -->
    <li class="red">two</li>
    <li class="red">three</li>
    <li class="blue">one</li> <!-- and this first child of blue -->
    <li class="blue">two</li>
    <li class="blue">three</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

Alv*_*aro 6

正如其他人所提到的那样:第一个孩子正在按照预期工作,作为父母的第一个孩子.

:first-child选择器用于选择指定的选择器,前提是它是父节点的第一个子节点.

来源:CSS:第一个子选择器

你可以像这样到达第一个.blue:

.red + .blue
Run Code Online (Sandbox Code Playgroud)

或者如果你想在.red之后得到所有的.blue

.red ~ .blue
Run Code Online (Sandbox Code Playgroud)

您可能希望使用:first-of-type选择第一个类型但是那些.blue必须是不同的HTML元素.

div.red:first-of-type {
    color:#F00;
}
div.red:last-of-type {
    color:#00F;
}
p.blue:first-of-type {
    color:#F00;
}
p.blue:last-of-type {
    color:#00F; 
}
Run Code Online (Sandbox Code Playgroud)
<div>
    <div class="red">one</div>
    <div class="red">two</div>
    <div class="red">three</div>
    <p class="blue">one</p>
    <p class="blue">two</p>
    <p class="blue">three</p>
</div>
Run Code Online (Sandbox Code Playgroud)