如何实现鼠标悬停<a>标签区域时切换图标颜色?
Fix: Change Icon Color When Hovering the Entire Link
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:
- 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;} - Add a new rule that targets the icon when the
<a>is hovered:
This selector works because it looks for the.sidebar .menu li a:hover .icon { color: #3d5654; }.iconelement inside an<a>tag that's being hovered. Since your<a>already gets a background color of#ecedf2on 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 .icontargets the icon element specifically when its parent<a>is hovered. - Since the
<a>tag is set todisplay: 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
相关产品推荐
相关产品推荐

