Does CSS work with the first child or with the last child with the class?

This question may be ridiculous, but I want to know this fact. I have an element liwith two classes (see below), but it does not work as I expected. Does anyone know the reason?

.red:first-child {
    color:#F00;
}
.blue:first-child {
    color:#00F; /* not working */
}
.red:last-child {
    color:#F00; /* not working */
}
.blue:last-child {
    color:#00F; 
}
<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 codeHide result
+4
source share
3 answers

As already mentioned, the first child works as expected, as the first child of the parent.

The first-child selector is used to select the specified selector only if it is the first child of its parent.

Source: CSS: first parent selector

You can achieve the first .blue as follows:

.red + .blue

or if you want to get all .blue after .red

.red ~ .blue

, : 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; 
}
<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>
Hide result
+6

. , , . THEN , , .

. .

0

, , ( , ):

  • .red.
  • .red (first-child).
  • .

.

EDIT:

The blue case is because CSS is always looking for the most accurate rule. If both rules have the same level of accuracy, the latter wins, so in this case, the gain .blue:last-childand .blue:first-childignored.

0
source

Source: https://habr.com/ru/post/1665485/


All Articles