CSS :hover 效果失效:容器悬停未实现向上移动
问题解决:CSS :hover 向上移动效果不生效
你的代码里hover效果失效的核心原因是错误使用了transform的方法:
- 你用了
scaleY(-20px),但scaleY()是用来沿Y轴缩放元素的,参数只能是数字(比如scaleY(0.8)是缩小至原尺寸的80%),不能带单位,更不是用来实现位移的。浏览器无法识别这个错误语法,所以hover完全没反应。 - 要实现元素向上移动,应该用
translateY()方法,参数是位移距离(带单位,比如-20px就是向上移动20px)。
另外补充:body设置position: absolute和宽高50%可能会导致页面可交互区域受限,建议改成min-height: 100vh来确保页面高度足够,避免hover区域异常。
修正后的完整代码:
<html> <title> test </title> <head> <style> .header { position: absolute; font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif; color:bisque; top:100px; left:300px; } body { /* 修正body样式,确保页面高度足够 */ min-height: 100vh; margin: 0; background-image: url(pexels2.jpg); background-size: cover; } .container1 { position: absolute; height: 330px; width: 330px; left: 100px; top: 250px; background-size: contain; transition: 2s; } /* 修正hover的transform方法 */ .container1:hover { transform: translateY(-20px); } </style> </head> <body> <div class="container1"> <img src="pexels-pick2.jpg" width="330px" height="330px"> </div> </body> </html>
内容的提问来源于stack exchange,提问作者Hrudai Nirmal
相关产品推荐
相关产品推荐

