如何用CSS实现hover时的动态缩放及角度变换动画?
实现图片Hover时的缩放+角度变换动画需求
我正在做一个项目,需要给四个图片选项添加hover时的动态缩放及角度变换动画,提升视觉体验,想要达到类似示例的效果。翻了YouTube和谷歌都没找到相关教程,附上现有代码,求指导实现方法!
示例效果:鼠标悬停时图片放大并带有角度变换的动态效果
现有代码
<html> <head> <title>Hello, World!</title> </head> <style> body { background-color: #eb3477; } .sel-btns { display: flex; justify-content: space-evenly; align-items: flex-end; } .box { margin-top: 100px; } .box { display: flex; border: solid; color: white; height: 50px; width: 65px; align-items: flex-end; border-radius: .5em; background: #d94c74; } img { position: relative; right: 45px; top: 5px; height: 150px; width: 150px; } </style> <body> <div class='wrapper'> <div class="sel-btns"> <div class="box"> <a href="#"><img src='https://svgshare.com/i/13sL.svg' title='ice cream' /></a> </div> <div class="box"> <a href="#"><img src='https://svgshare.com/i/13sL.svg' title='ice cream' /></a> </div> <div class="box"> <a href="#"><img src='https://svgshare.com/i/13sL.svg' title='ice cream' /></a> </div> <div class="box"> <a href="#"><img src='https://svgshare.com/i/13sL.svg' title='ice cream' /></a> </div> </div> </div> </body> </html>
实现方法
只需要通过CSS的transition和transform属性就能实现需求,具体步骤如下:
- 给图片添加过渡动画属性,让变换过程更平滑
- 给
.box的hover状态下的图片设置缩放和旋转效果 - 调整
z-index确保hover的图片在最上层,避免被其他元素遮挡
修改后的完整代码
<html> <head> <title>Hello, World!</title> </head> <style> body { background-color: #eb3477; } .sel-btns { display: flex; justify-content: space-evenly; align-items: flex-end; } .box { margin-top: 100px; cursor: pointer; } .box { display: flex; border: solid; color: white; height: 50px; width: 65px; align-items: flex-end; border-radius: .5em; background: #d94c74; } img { position: relative; right: 45px; top: 5px; height: 150px; width: 150px; /* 平滑过渡动画,时长和缓动函数可按需调整 */ transition: all 0.3s ease; z-index: 1; } /* 鼠标悬停时的变换效果 */ .box:hover img { /* scale控制缩放比例,rotate控制旋转角度,可自定义参数 */ transform: scale(1.2) rotate(5deg); z-index: 10; } </style> <body> <div class='wrapper'> <div class="sel-btns"> <div class="box"> <a href="#"><img src='https://svgshare.com/i/13sL.svg' title='ice cream' /></a> </div> <div class="box"> <a href="#"><img src='https://svgshare.com/i/13sL.svg' title='ice cream' /></a> </div> <div class="box"> <a href="#"><img src='https://svgshare.com/i/13sL.svg' title='ice cream' /></a> </div> <div class="box"> <a href="#"><img src='https://svgshare.com/i/13sL.svg' title='ice cream' /></a> </div> </div> </div> </body> </html>
关键代码说明
transition: all 0.3s ease: 给图片的所有属性变化添加0.3秒的平滑过渡,ease缓动函数让动画更自然transform: scale(1.2) rotate(5deg): 鼠标悬停时,图片放大至原尺寸的1.2倍,同时顺时针旋转5度,可根据需求修改缩放比例和旋转角度z-index: 10: 确保hover的图片在其他图片上方,避免被遮挡
内容的提问来源于stack exchange,提问作者Sofiela Marquez
相关产品推荐
相关产品推荐

