简体   繁体   中英

How to use nth-child with :hover to style multiple children?

JS Fiddle for easier debugging: http://jsfiddle.net/GregsFiddle/WyC7Y/1/

I am trying to setup this css so when you mouseover nine, nine and below get their bg color changed.

Mouseover 5, and 5 and below have their color changed. You get the idea. I am not sure how to use the nth-child(-n+#) selector with :hover.

ol.motivationBox .motivationBars li:nth-child(10):hover:nth-child(-n+9) {
background-color: #008cba;
}

That bit of code is not functioning. What did I format incorrectly?

Since you currently can't transverse the DOM tree, this seems to be the only thing possible in pure CSS.

Basically, the general sibling combinator, ~ , allows us to access all succeeding sibling elements.

UPDATED EXAMPLE HERE

ol.motivationBox .motivationBars:hover ~ .motivationBars,
ol.motivationBox .motivationBars:hover {
    background-color: #008cba;
}

.. if you wanted to use jQuery and select preceding sibling elements, you could use this:

ALTERNATIVE EXAMPLE HERE

$('.motivationBox .motivationBars').hover(
    function(){
        $(this).prevAll().andSelf().addClass('active');
    },
    function(){
        $('.active').removeClass('active');
    }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM