Greg L
Greg L

Reputation: 468

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?

Upvotes: 2

Views: 539

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240898

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

Upvotes: 3

Related Questions