hover effect on another class in css


I have menu which the active item has an active class on load, which changes its background.

The hover of other items change the background of hovered item.

  <li class="active"></li>

  li:hover, li.active {background:black}

Is there any way to remove active class background on other items hover in pure CSS. something like:

li.hover .active {background:none}

This works if active is under li, but doesn't work here.

Problem courtesy of: Ali


This isn't reliably possible with CSS, as CSS can only affect elements that appear later in the DOM, not previously, so hovering over the first li can affect the current li.active element with the following CSS:

li:hover ~ li.active {
    background-color: #f00; /* or whatever */

JS Fiddle demo.

But hovering over the third li cannot affect the same li.active element.

However, the following would work:

ul:hover li.active {
    background-color: transparent;

JS Fiddle demo.

Solution courtesy of: David Thomas


Try this:

ul:not(:hover)>li.active { background: black; }
ul>li.active:not(:hover) { background: none; }

This has a few conditions:

  1. A browser which supports the :not pseudo-tag
  2. The ul must not have too much padding or empty space, otherwise you could activate the :hover of the ul without hovering over any lis
Discussion courtesy of: Nathan MacInnes

This recipe can be found in it's original form on Stack Over Flow.