With existing markup, is it possible to set styles in CSS for the last span of the "c2" class inside the element with the ID "a" (marked with an exclamation mark)?

<div id = "a"> <span class = "c1">...</span> <span class = "c1">...</span> <span class = "c2">...</span> <span class = "c2">...</span>! <span class = "c1">...</span> </div> 

    2 answers 2

    The pseudo-class :last-child sets the style for the last element of its parent.

    This means that it works only on the last element, from all child elements, and not on the last element for a class or some other attribute.

    In this case, it is better to use another pseudo-class :nth-child()

     #a span:nth-child(4) /* отсчет от одного, а не от нуля! */ 

    Example

     span { display: block; margin: 10px; font-size: 25px; } #a span:nth-child(4) { color: red; } 
     <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JS Bin</title> </head> <body> <div id="a"> <span class="c1">1...</span> <span class="c1">2...</span> <span class="c2">3...</span> <span class="c2">4...</span> <span class="c1">5...</span> </div> </body> </html> 

    • Not very well in the event that, like me, the number of the necessary element is not immediately known. We only know that this is the last element of the class C2 inside a common ancestor. - nup
    • @nup, use js in this case, otherwise your task will not be solved otherwise (in this case) - ThisMan

    If everything is dynamically displayed, use the jquery method .last http://jquery.page2page.ru/index.php5/Search_of the last_element_in_set