According to the level 3 specification of css, for the pseudoclass% co_of% to work, there must be a container element of the selector to which it is applied.
In theory the same principle applies for :last-child
.linea {
position: relative;
width: 40%;
height: 30px;
background-color: orange;
left: 0;
display: block;
}
.linea:last-child {
background-color: green;
}
.linea:nth-child(2) {
background-color: blue;
}
<div>
<div class="linea">Línea 1</div>
<div class="linea">Línea 2</div>
<div class="linea">Línea 3</div>
<div class="linea">Línea 4</div>
<div class="linea">Línea 5</div>
</div>
If there are other elements than those covered by the selector, apparently the "pseudoclass" stops working, but it is not, it is simply being used incorrectly according to the CSS specification, since :nth-child
was created to select the last element of a certain level, not to apply to the last element of a specific class as you intend to do:
.linea {
position: relative;
width: 40%;
height: 30px;
background-color: orange;
left: 0;
display: block;
}
.linea:last-child {
background-color: green;
}
.linea:nth-child(2) {
background-color: blue;
}
<div>
<div class="linea">Línea 1</div>
<div>Texto</div>
<div class="linea">Línea 2</div>
<div class="linea">Línea 3</div>
<div>Texto</div>
<div class="linea">Línea 4</div>
<div>Texto</div>
<div class="linea">Línea 5</div>
<div>Más texto</div>
</div>