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

如何实现鼠标悬停<a>标签区域时切换图标颜色?

The issue with your current setup is that your CSS selector only targets the icon when it's directly hovered, not when the parent <a> tag is hovered. To fix this, you need to adjust the selector to target the icon when its parent <a> is in a hover state.

Step-by-Step Solution:

  1. Remove the existing icon-only hover rule:
    /* Delete this line, it's no longer needed */
    .sidebar .menu li a .icon:hover{background: #ecedf2;color: #3d5654;}
    
  2. Add a new rule that targets the icon when the <a> is hovered:
    .sidebar .menu li a:hover .icon {
      color: #3d5654;
    }
    
    This selector works because it looks for the .icon element inside an <a> tag that's being hovered. Since your <a> already gets a background color of #ecedf2 on hover, you don't need to set a separate background for the icon—it will inherit the <a>'s hover background automatically.

Updated Full CSS:

Here's how your complete CSS should look after the changes:

* { list-style: none; text-decoration: none; margin: 0; padding: 0; box-sizing: border-box; font-family: 'Jost', sans-serif; } 
*, *:before, *:after { box-sizing: inherit; } 
body { height: 100vh; width: 100wh; padding: 0; margin: 0; font-size: 1rem; font-weight: 300; line-height: 1.6; display: grid; grid-template-columns: auto 8fr; grid-template-rows: 80px auto 50px; grid-template-areas: 'header header' 'sidebar main' 'footer footer'; } 
.sidebar { grid-area: sidebar; width: 260px; background: #2c343b; height: 100%; } 
.sidebar .menu { padding-right: 30px; padding-left: 20px; margin: 0; overflow: auto; transition: all 0.5s; } 
.sidebar .menu li a { color: #ecedf2; display: block; width: 100%; line-height: 60px; text-decoration: none; padding: 15px; text-transform: uppercase; letter-spacing: 2px; margin-bottom: 1px; transition: 0.5s; } 
.sidebar .menu li a .icon { color: #ecedf2; width: 25px; display: inline-block; } 
.sidebar .menu li a:hover, .sidebar .menu li a.active { background: #ecedf2; color: #3d5654; }
/* New rule added */
.sidebar .menu li a:hover .icon {
  color: #3d5654;
}

Why This Works:

  • The selector .sidebar .menu li a:hover .icon targets the icon element specifically when its parent <a> is hovered.
  • Since the <a> tag is set to display: block, hovering anywhere within its bounds (including the space around the icon and text) will trigger the hover state.
  • The icon's color will now match the text color (#3d5654) when the link is hovered, making it visible against the light background.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 20:42:38