Search code examples
htmlcsscss-selectors

Apply CSS to last element of specific class


I want to apply some CSS to the last blog-post. The problem is that the last element in the div 'blog-posts' is the same type of element as the 'blog-post' divs.

I've tried:

  • last-of-type
  • last-child

HTML:

<div class="blog-posts">
    <div class="blog-post"></div>
    <div class="blog-post"></div>
    <div class="blog-post"></div>
    <div class="blog-post"></div>
    <div class="f03-456245"></div>
</div>

CSS:

.blog-post:last-child{
    //do some css
}

Solution

  • Last element using .class is not possible. In your case you can use nth-last-child property.

     .blog-posts div:nth-last-child(2) {
       background: #ff0000;
     }
    

    DEMO