A CSS selector to get last visible div

Vishal Shah picture Vishal Shah · Mar 11, 2011 · Viewed 182k times · Source

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).

Answer

Surreal Dreams picture Surreal Dreams · Mar 11, 2011

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');