Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A CSS selector to get last visible div

A tricky CSS selector question, don't know if it's even possible.

Lets say this is the HTML layout:

<div></div> <div></div>   <div></div>   <div style="display:none"></div> <div style="display:none"></div>   

I want to select the last div, which is displayed (ie. not display:none) which would be the third div in the given example. Mind you, the number of divs on the real page can differ (even the display:none ones).

like image 999
Vishal Shah Avatar asked Mar 11 '11 15:03

Vishal Shah


People also ask

How do I target a last div in CSS?

The :last-child selector allows you to target the last element directly inside its containing element. 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.

Is CSS selector visible?

The :visible selector selects every element that is currently visible. Visible elements are elements that are not: Set to display:none. Form elements with type="hidden"

How do you select the last class in CSS?

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


1 Answers

You could select and style this with JavaScript or jQuery, but CSS alone can't do this.

For example, if you have jQuery implemented on the site, you could just do:

var last_visible_element = $('div:visible:last'); 

Although hopefully you'll have a class/ID wrapped around the divs you're selecting, in which case your code would look like:

var last_visible_element = $('#some-wrapper div:visible:last'); 
like image 101
Surreal Dreams Avatar answered Sep 19 '22 14:09

Surreal Dreams