Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 249
Kevin Restiaens Avatar asked Aug 27 '14 06:08

Kevin Restiaens


People also ask

How do you choose the last element?

The :last selector selects the last element. Note: This selector can only select one single element. Use the :last-child selector to select more than one element (one for each parent). This is mostly used together with another selector to select the last element in a group (like in the example above).

How do I select the first and last child in CSS?

:first-child means "select this element if it is the first child of its parent". :last-child means "select this element if it is the last child of its parent". Only element nodes (HTML tags) are affected, these pseudo-classes ignore text nodes.

How do I select the first and last element in CSS?

The first <div/> element with class milestone can be selected with the :first-of-type selector and the last <div/> element with class milestone can be selected with the :last-of-type selector. We use the above two selectors to round off the borders of the first and last milestones.

What is the difference between last child and last-of-type in CSS?

Both selectors work in the same way but have a slight difference i.e the last type is less specified than the last-child selector. Example: This example implements the :last-child selector. Output: After compiling the SASS source code you will get this CSS code.


Video Answer


1 Answers

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

like image 160
Suresh Ponnukalai Avatar answered Oct 14 '22 01:10

Suresh Ponnukalai