设置全局背景图后按钮hover失效,移除背景图后效果正常的求助
全局背景图配置导致按钮hover样式失效问题
现象记录
- 页面内两个位于背景图上层的按钮,编写完hover样式后始终无预期的样式变化
- 注释掉页面背景图相关代码后,按钮hover效果可正常触发
- 多浏览器测试结果一致,排除单浏览器兼容性问题
关联代码
页面结构
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Harry Fitness</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container top-container"> <div class="left"> <img src="logo.jpg" alt=""> </div> <div class="mid"> <ul> <a href="#"><li>Home</li></a> <a href="#"><li>Products</li></a> <a href="#"><li>Calender</li></a> <a href="#"><li>About Us</li></a> </ul> </div> <div class="right"> <button class="btn">Call Us Now</button> <button class="btn">Email Us</button> </div> </div> </body> </html>
存在问题的样式代码
/* 通配选择器给全局所有元素设置了背景图 */ *{ margin: 0px; padding: 0px; background-image: url(athletic-young-female-runner-jogger-stylish-sportswear-running-against-blank-wall-having-concentrated-focused-look-going-win-sprint-endurance-race.jpg); background-size: 2000px 1000px ; background-repeat: no-repeat; color: black } .left{ display: inline-block; border: 2px solid red; position: absolute; } .left img{ height: 100px; width: 110px; } .mid{ margin-top: 20px; border: 2px solid green; display: inline-block; width: 33%; position: absolute; margin-left: 600px; font-size: 20px; } .mid li{ list-style: none; float: left; margin-left: 50px; } .mid li a:hover{ background-color: white; } .right{ margin-top: 20px; display: inline-block; position: absolute; right: 34px; top:22px border: 2px solid yellow; } .btn{ margin: 0px 9px; border-radius: 10px; padding: 10px 10px; background-color: blanchedalmond; cursor: pointer; font-size: 15px; } /* 写好的hover规则始终不生效 */ .btn:hover{ background-color: rgb(31, 30, 30); }
对照测试结果
将通配选择器内的背景图、背景尺寸配置注释掉,其余代码完全不变时:
*{ margin: 0px; padding: 0px; /* background-image: url(athletic-young-female-runner-jogger-stylish-sportswear-running-against-blank-wall-having-concentrated-focused-look-going-win-sprint-endurance-race.jpg); background-size: 2000px 1000px ; */ background-repeat: no-repeat; color: black }
此时按钮hover效果可正常触发,背景色可按预期切换。测试需求为:保留页面背景图正常显示的前提下,恢复按钮hover交互效果。
问题根因
- 通配选择器
*的滥用是问题核心:*会匹配页面内所有元素,包括两个按钮,给按钮本身也强制挂载了同一张页面背景图。 - CSS背景渲染层级中,背景图位于背景色上层:按钮被挂上全局背景图后,hover阶段修改的
background-color始终被上层的背景图遮挡,视觉上看不到颜色变化,因此表现为hover样式失效。 - 注释掉全局背景图配置后,按钮不再被挂载多余背景图,hover修改的背景色无遮挡,效果自然恢复。
修复方案
- 拆分通配选择器的职责:只把全局边距重置的配置保留在
*选择器内,将原本写在*里的页面背景相关配置,单独移到body选择器下,仅给页面根元素设置背景图,不再给所有子元素强制挂载:*{ margin: 0; padding: 0; } body { background-image: url(athletic-young-female-runner-jogger-stylish-sportswear-running-against-blank-wall-having-concentrated-focused-look-going-win-sprint-endurance-race.jpg); background-size: 2000px 1000px; background-repeat: no-repeat; color: black; } - 修复原代码中的语法错误:
.right选择器内top:22px行尾缺少分号,会导致后续border: 2px solid yellow样式解析失败,补充分号即可。
内容的提问来源于stack exchange,提问作者healer man115
相关产品推荐
相关产品推荐

