hover effect on another class in css

2020-04-14 07:18发布

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.

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

<style>
  li:hover, li.active {background:black}
</style>

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.

标签: css
3条回答
够拽才男人
2楼-- · 2020-04-14 07:40

This worked for me :

.dvchange1 {
  color:#fff;
    }
    .dvOne:hover .dvchange2 {
        color:#000;
    }
 <div class="dvchange1 dvchange2">
    <span class="">
    Hello
    <span>
    </div>

查看更多
孤傲高冷的网名
3楼-- · 2020-04-14 07:48

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
查看更多
Viruses.
4楼-- · 2020-04-14 07:50

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.

查看更多
登录 后发表回答