Hover on nested item can affect its parent?

2019-06-12 17:07发布

I have a menu using pure CSS, hover a parent li item display the the nested list. A simplified example:

  <ul id="menu-top" >
    <li class="menu-item">
      <a href="http://localhost/wp5/forums/">Forums</a>
      <ul class="sub-menu">
        <li><a href="http://localhost/wp5/register/">Register</a></li>
        <li><a href="http://localhost/wp5/activate/">Activate</a></li>
        <li><a href="http://localhost/wp5/members/">Members</a></li>
      </ul>
    </li>
  </ul>

The css:

.navigation ul.menu li:hover { background: #ccc} //hover the parent item changes it bg color

.navigation ul.sub-menu li {
 display:none;
}

.navigation ul li:hover > ul.sub-menu li { display: block; }

It works ok, but I'm trying to add an "persistent" effect, I want keep the parent style set when hovering also the sub-item.

I tried this but can't get working:

.navigation ul.sub-menu li:hover > .navigation ul.menu li { background: #ccc}

I don't know if this is possible without javscript or else, also can't find anything about using ">" in CSS.

THanks for any help

2条回答
Emotional °昔
2楼-- · 2019-06-12 17:31
.menu-item:hover {
     background-color:#ccc;
}
.sub-menu li:hover {
     background-color:#666;
}
查看更多
forever°为你锁心
3楼-- · 2019-06-12 17:55

:hover is triggered on all ancestors of the element that is being hovered over, so .navigation ul.menu li:hover { background: #ccc; } should work just fine.

Alternatively, someday we should be able to use :has().

查看更多
登录 后发表回答