A CSS selector to get last visible div

2019-01-04 09:48发布

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

9条回答
迷人小祖宗
2楼-- · 2019-01-04 09:50

The real answer to this question is, you can't do it. Alternatives to CSS-only answers are not correct answers to this question, but if JS solutions are acceptable to you, then you should pick one of the JS or jQuery answers here. However, as I said above, the true, correct answer is that you cannot do this in CSS reliably unless you're willing to accept the :not operator with the [style*=display:none] and other such negated selectors, which only works on inline styles, and is an overall poor solution.

查看更多
Animai°情兽
3楼-- · 2019-01-04 09:52

This worked for me.

.alert:not(:first-child){
    margin: 30px;
}
查看更多
等我变得足够好
4楼-- · 2019-01-04 10:00

I think it's not possible to select by a css value (display)

edit:

in my opinion, it would make sense to use a bit of jquery here:

$('#your_container > div:visible:last').addClass('last-visible-div');
查看更多
男人必须洒脱
5楼-- · 2019-01-04 10:05

in other way, you can do it with javascript , in Jquery you can use something like:

$('div:visible').last()

*reedited

查看更多
一夜七次
6楼-- · 2019-01-04 10:06

It is not possible with CSS, however you could do this with jQuery.

JSFIDDLE DEMO

jQuery:

$('li').not(':hidden').last().addClass("red");

HTML:

<ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li class="hideme">Item 4</li>    
</ul>

CSS:

.hideme {
    display:none;
}

.red {
    color: red;
}

jQuery (previous solution):

var $items = $($("li").get().reverse());

$items.each(function() {

    if ($(this).css("display") != "none") {
        $(this).addClass("red");
        return false;
    }

});
查看更多
一夜七次
7楼-- · 2019-01-04 10:08

There is a pure css solution (CSS3) if your div is hidden using "style" attribute

div:not([style*="display: none"]):last-child{ /* bla */}

Note the space between "display:" and "none", if you can't say exactly if there is a space in the attribute or not, you can do the selector like this:

div:not([style*="display:none"]):not([style*="display: none"]):last-child{ /* bla */}

jQuery is king, but CSS3 solutions are god

查看更多
登录 后发表回答