Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css selector for last div with a specific class

I have this situation:

<div class="container">
 <div class="pagination-bar"></div>
 <div class="article"></div>
 [..]
 <div class="article"></div>
 <div class="pagination-bar"></div>
</div>

and this CSS:

.article {
 margin-bottom:20px;
}

What if I want the pagination-bar close to the last "article" div without the 20px margin?

UPDATED [see the pagination-bar both on the top and to the end of the container div]

like image 968
luca Avatar asked Jul 09 '11 23:07

luca


People also ask

How do you get the last element of a class in CSS?

Solution with CSS To select the last element of a specific class, you can use the CSS :last-of-type pseudo-class.

How could you use a selector to choose a specific element with a specific class?

class selector selects elements with a specific class attribute. To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class.

How do you style the last class in CSS?

The :last-of-type selector allows you to target the last occurence of an element within its container. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.


2 Answers

You can have it like this, also compatible with IE7

div.article + div.article {
    margin-top:20px;
}

This adds the margin on top except for the very first article.

like image 136
emboss Avatar answered Nov 12 '22 14:11

emboss


Try this:

.container > div:nth-last-child(2) + .pagination-bar { color: red; }

:nth-last-child will give you the second to last element in the container and the + selector will give you the adjacent element with class .pagination-bar.

Here's my test: http://jsfiddle.net/gYM7x/

With that said, browser support is limited for this pseudo class.

like image 36
Jesse Bunch Avatar answered Nov 12 '22 15:11

Jesse Bunch