You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CSS中实现悬停子元素时保持父元素激活状态?

How to Keep Parent Element Active When Hovering Over Child Submenu?

Hey there! Let's tackle this issue—you want the parent menu item to stay active when hovering over its submenu, right? The problem with your current CSS is that the selector you wrote for this effect is structured incorrectly, and CSS doesn’t support direct parent selectors. But there’s a straightforward fix using the parent <li>’s hover state, since the submenu is its child element.

First, let’s recap your HTML structure (fixed the closing </ul> typo for clarity):

<nav class="desktop-menu">
  <ul class="navbar-nav">
    <li><a href="#">About</a></li>
    <li>
      <a title="Business Lines" href="#">Business Lines</a>
      <ul role="menu" class="dropdown-menu sub-nav">
        <li><a title="Energy" href="#">Energy</a></li>
      </ul>
    </li>
  </ul>
</nav>

Here’s the adjusted CSS that will make the parent stay active when hovering over the submenu:

/* Style parent link when its parent <li> is hovered (covers both link hover and submenu hover) */
.desktop-menu .navbar-nav>li:hover>a {
  color: #fff;
  background: #67686b;
}

/* Keep your existing submenu styles */
.desktop-menu .dropdown-menu {
  min-width: 220px;
  position: absolute;
  top: 100%;
  border: none;
  background: #67686b;
  color: #fff;
  box-shadow: none;
}

.desktop-menu .dropdown-menu li a:hover {
  color: #FBB914;
}

Why this works:

When you hover over the submenu, your mouse is still within the bounds of the parent <li> element. This means the parent <li> remains in the :hover state the entire time. By targeting the parent <a> using the parent <li>’s hover state (instead of just the <a>’s own hover state), we ensure the parent stays highlighted whether you’re hovering the link directly or navigating the submenu.

You can remove your original attempt at the parent active CSS (the last rule in your code) because this approach handles both scenarios seamlessly.

内容的提问来源于stack exchange,提问作者Zain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:36:42