HTML悬停图片错位求助:博客按钮悬停图覆盖上方按钮
解决按钮悬停图错位问题
问题根源
你的所有悬停图都用了position: absolute,且均相对于父容器.buttonlinks定位,但.buttonlinks高度仅30px,同时你没给每个按钮单独设置定位容器,导致所有悬停图都堆在容器顶部,出现错位。另外,直接给透明的悬停图加hover事件,鼠标很难准确触发(因为它初始状态是不可见的)。
修复方案
- 给每个按钮单独创建容器,把基础图和悬停图放在同一个容器内,让悬停图相对于自身按钮容器定位。
- 用通用CSS类减少重复代码,将hover事件绑定到按钮容器上,确保鼠标移到按钮区域就触发效果。
修改后的代码
HTML部分
<!doctype html> <html lang="en"> <head> <link rel="stylesheet" href="你的CSS文件路径"> </head> <body> <!-- Left Section --> <div class="column left" style="background-color: rgba(125, 77, 77, 0)"> <div class="button-group"> <!-- About Me按钮 --> <a href="otherpages/about-me.html" class="button-item"> <img src="buttons/about-me.png" alt="About Me Button" class="base-btn"> <img src="buttons/about-me-hover.png" alt="About Me Hover Button" class="hover-btn"> </a> <!-- Blog按钮 --> <a href="otherpages/blog.html" class="button-item"> <img src="buttons/blog.png" alt="Blog Button" class="base-btn"> <img src="buttons/blog-hover.png" alt="Blog Hover Button" class="hover-btn"> </a> <!-- Interests按钮 --> <a href="buttons/interests.png" class="button-item"> <img src="buttons/interests.png" alt="Interests Button" class="base-btn"> <img src="buttons/interests-hover.png" alt="Interests Hover Button" class="hover-btn"> </a> </div> </div> <div class="column null" style="background-color: rgba(125, 77, 77, 0)"> <p></p> </div> </body> </html>
CSS部分
/* 按钮组容器,控制整体宽度 */ .button-group { width: 300px; /* 让按钮垂直排列 */ display: flex; flex-direction: column; gap: 5px; /* 按钮之间的间距,可按需调整 */ } /* 单个按钮容器,设置相对定位作为悬停图的定位基准 */ .button-item { position: relative; width: 100%; height: 30px; display: block; /* 确保a标签占满容器 */ } /* 基础按钮和悬停按钮的通用样式 */ .button-item img { width: 100%; height: 100%; position: absolute; left: 0; top: 0; transition: opacity .3s ease-in-out; } /* 默认显示基础按钮,隐藏悬停按钮 */ .button-item .hover-btn { opacity: 0; } /* 鼠标移到按钮容器上时,切换按钮显示状态 */ .button-item:hover .hover-btn { opacity: 1; } .button-item:hover .base-btn { opacity: 0; }
关键说明
- 每个按钮用
.button-item容器包裹并设置position: relative,里面的悬停图(position: absolute)会相对于这个容器定位,不会跑到其他按钮位置。 - 把hover事件绑定到
.button-item上,只要鼠标碰到按钮区域就触发效果,解决了之前悬停图透明时无法触发hover的问题。 - 用Flex布局让按钮垂直排列,比手动设置top值更灵活,还能通过
gap快速调整按钮间距。
内容的提问来源于stack exchange,提问作者MetalZS
相关产品推荐
相关产品推荐

